Nix 2.36.0
Nix, the purely functional package manager; unstable internal interfaces
Loading...
Searching...
No Matches
logging.hh
Go to the documentation of this file.
1#pragma once
3
4#include "nix/util/error.hh"
7#include "nix/util/finally.hh"
8#include "nix/util/fun.hh"
9
10#include <filesystem>
11#include <span>
12#include <type_traits>
13
14#include <nlohmann/json_fwd.hpp>
15
16namespace nix {
17
18/* TODO: Make these enum classes. */
19
20typedef enum {
21 actUnknown = 0,
22 actCopyPath = 100,
23 actFileTransfer = 101,
24 actRealise = 102,
25 actCopyPaths = 103,
26 actBuilds = 104,
27 actBuild = 105,
28 actOptimiseStore = 106,
29 actVerifyPaths = 107,
30 actSubstitute = 108,
31 actQueryPathInfo = 109,
32 actPostBuildHook = 110,
33 actBuildWaiting = 111,
34 actFetchTree = 112,
35 /* A source path is being copied into the store, or (in dry-run mode) hashed
36 to compute its store path, via `fetchToStore()`. This backs eval-time path
37 coercion (`"${./file}"`, `src = ./.`), `builtins.path`, and similar. The
38 activity brackets the operation. Fields:
39 [0] = source path (string)
40 [1] = whether the path is only being hashed in a dry run rather than
41 actually copied (1 = hashing, 0 = copying) (int)
42 The resulting store path is only known once the operation completes and is
43 delivered via a resFetchToStore result. */
44 actFetchToStore = 113,
45 actLast = actFetchToStore
46} ActivityType;
47
48typedef enum {
49 resFileLinked = 100,
50 resBuildLogLine = 101,
51 resUntrustedPath = 102,
52 resCorruptedPath = 103,
53 resSetPhase = 104,
54 resProgress = 105,
55 resSetExpected = 106,
56 resPostBuildLogLine = 107,
57 resFetchStatus = 108,
58 /* The resulting store path of an actFetchToStore activity, emitted once the
59 operation completes. Fields: [0] = store path (string). */
60 resFetchToStore = 109,
61 resLast = resFetchToStore,
62} ResultType;
63
64typedef uint64_t ActivityId;
65
66class LoggerSettings : public Config
67{
68 void anchor() override;
69
70public:
71 Setting<bool> showTrace{
72 this,
73 false,
74 "show-trace",
75 R"(
76 Whether Nix should print out a stack trace in case of Nix
77 expression evaluation errors.
78 )"};
79
81 this,
82 {},
83 "json-log-path",
84 R"(
85 A file or unix socket to which JSON records of Nix's log output are
86 written, in the same format as `--log-format internal-json`
87 (without the `@nix ` prefixes on each line).
88 Concurrent writes to the same file by multiple Nix processes are not supported and
89 may result in interleaved or corrupted log records.
90 )"};
91};
92
93extern LoggerSettings loggerSettings;
94
95class Logger
96{
97 friend struct Activity;
98
99public:
100 /* Note that there are no members and invariants in the class itself
101 inheriting is fine, because slicing won't post any issues. There are
102 public constructors for implicit conversions and convenience. */
103 struct Field : public std::variant<uint64_t, std::string>
104 {
105 Field(const std::string & s)
106 : variant(s)
107 {
108 }
109
110 Field(std::string && s)
111 : variant(std::move(s))
112 {
113 }
114
115 Field(const char * s)
116 : variant(s)
117 {
118 }
119
120 Field(uint64_t i)
121 : variant(i)
122 {
123 }
124 };
125
126 virtual ~Logger();
127
128 virtual void stop() {};
129
134 {
135 Finally<fun<void()>> _finalize;
136 };
137
138 Suspension suspend();
139
140 std::optional<Suspension> suspendIf(bool cond);
141
142 virtual void pause() {};
143 virtual void resume() {};
144
145 // Whether the logger prints the whole build log
146 virtual bool isVerbose()
147 {
148 return false;
149 }
150
151 /* Note: logging functions must be noexcept, since they're often
152 called in contexts where exceptions cannot be handled (such as
153 in completion callbacks or destructors). Implementations should
154 handle failure to write the message (e.g. by ignoring it or
155 disabling the logger). */
156 virtual void log(Verbosity lvl, std::string_view s) noexcept = 0;
157
158 void log(std::string_view s) noexcept
159 {
160 log(lvlInfo, s);
161 }
162
163 virtual void logEI(const ErrorInfo & ei) noexcept = 0;
164
165 void logEI(Verbosity lvl, ErrorInfo ei) noexcept
166 {
167 ei.level = lvl;
168 logEI(ei);
169 }
170
171 virtual void warn(const std::string & msg) noexcept;
172
173 virtual void startActivity(
174 ActivityId act,
175 Verbosity lvl,
176 ActivityType type,
177 const std::string & s,
178 std::span<const Field> fields,
179 ActivityId parent) noexcept
180 {
181 }
182
183 virtual void stopActivity(ActivityId act) noexcept {};
184
185 virtual void result(ActivityId act, ResultType type, std::span<const Field> fields) noexcept {}
186
187 virtual void result(ActivityId act, ResultType type, const nlohmann::json & json) noexcept {}
188
189 virtual void writeToStdout(std::string_view s);
190
191 template<typename... Args>
192 inline void cout(const Args &... args)
193 {
194 writeToStdout(fmt(args...));
195 }
196
201 void writeStyledToStdout(std::string_view s);
202
203 template<typename... Args>
204 inline void coutStyled(const Args &... args)
205 {
206 writeStyledToStdout(fmt(args...));
207 }
208
209 virtual std::optional<char> ask(std::string_view s)
210 {
211 return {};
212 }
213
214 virtual void setPrintBuildLogs(bool printBuildLogs) {}
215};
216
217ActivityId getCurActivity();
218void setCurActivity(const ActivityId activityId);
219
220struct Activity
221{
222 Logger & logger;
223
224 const ActivityId id;
225
226 Activity(
227 Logger & logger,
228 Verbosity lvl,
229 ActivityType type,
230 const std::string & s = "",
231 std::span<const Logger::Field> fields = {},
232 ActivityId parent = getCurActivity());
233
234 Activity(
235 Logger & logger,
236 ActivityType type,
237 std::span<const Logger::Field> fields = {},
238 ActivityId parent = getCurActivity())
239 : Activity(logger, lvlError, type, "", fields, parent)
240 {
241 }
242
243 Activity(const Activity & act) = delete;
244
245 ~Activity();
246
247 void progress(uint64_t done = 0, uint64_t expected = 0, uint64_t running = 0, uint64_t failed = 0) const
248 {
249 result(resProgress, done, expected, running, failed);
250 }
251
252 void setExpected(ActivityType type2, uint64_t expected) const
253 {
254 result(resSetExpected, type2, expected);
255 }
256
257 template<typename... Args>
258 requires(!(std::is_constructible_v<std::span<const Logger::Field>, std::remove_cvref_t<Args>> || ...))
259 void result(ResultType type, Args &&... args) const
260 {
261 std::array<Logger::Field, sizeof...(args)> fields = {std::forward<Args>(args)...};
262 result(type, fields);
263 }
264
265 void result(ResultType type, std::span<const Logger::Field> fields) const
266 {
267 logger.result(id, type, fields);
268 }
269
270 friend class Logger;
271};
272
273struct PushActivity
274{
275 const ActivityId prevAct;
276
277 PushActivity(ActivityId act)
278 : prevAct(getCurActivity())
279 {
280 setCurActivity(act);
281 }
282
283 ~PushActivity()
284 {
285 setCurActivity(prevAct);
286 }
287};
288
289extern Logger * logger;
290
291std::unique_ptr<Logger> makeSimpleLogger(bool printBuildLogs = true);
292
298std::unique_ptr<Logger>
299makeTeeLogger(std::unique_ptr<Logger> mainLogger, std::vector<std::unique_ptr<Logger>> && extraLoggers);
300
301std::unique_ptr<Logger> makeJSONLogger(Descriptor fd, bool includeNixPrefix = true);
302
303std::unique_ptr<Logger> makeJSONLogger(const std::filesystem::path & path, bool includeNixPrefix = true);
304
305void applyJSONLogger();
306
310std::optional<nlohmann::json> parseJSONMessage(std::string_view msg, std::string_view source);
311
316 const nlohmann::json & json,
317 const Activity & act,
318 std::map<ActivityId, Activity> & activities,
319 std::string_view source,
320 bool trusted);
321
326 std::string_view msg,
327 const Activity & act,
328 std::map<ActivityId, Activity> & activities,
329 std::string_view source,
330 bool trusted);
331
332inline bool handleJSONLogMessage(
333 const std::string & msg,
334 const Activity & act,
335 std::map<ActivityId, Activity> & activities,
336 std::string_view source,
337 bool trusted)
338{
339 return handleJSONLogMessage(std::string_view(msg), act, activities, source, trusted);
340}
341
345extern Verbosity verbosity;
346
353#define logErrorInfo(level, errorInfo...) \
354 do { \
355 if ((level) <= nix::verbosity) { \
356 logger->logEI((level), errorInfo); \
357 } \
358 } while (0)
359
360#define logError(errorInfo...) logErrorInfo(lvlError, errorInfo)
361#define logWarning(errorInfo...) logErrorInfo(lvlWarn, errorInfo)
362
368#define printMsgUsing(loggerParam, level, args...) \
369 do { \
370 auto __lvl = level; \
371 if (__lvl <= nix::verbosity) { \
372 loggerParam->log(__lvl, fmt(args)); \
373 } \
374 } while (0)
375#define printMsg(level, args...) printMsgUsing(logger, level, args)
376
377#define printError(args...) printMsg(lvlError, args)
378#define notice(args...) printMsg(lvlNotice, args)
379#define printInfo(args...) printMsg(lvlInfo, args)
380#define printTalkative(args...) printMsg(lvlTalkative, args)
381#define debug(args...) printMsg(lvlDebug, args)
382#define vomit(args...) printMsg(lvlVomit, args)
383
387template<typename... Args>
388inline void warn(const std::string & fs, const Args &... args)
389{
390 boost::format f(fs);
391 formatHelper(f, args...);
392 logger->warn(f.str());
393}
394
395#define warnOnce(haveWarned, args...) \
396 if (!haveWarned) { \
397 haveWarned = true; \
398 warn(args); \
399 }
400
401void writeToStderr(std::string_view s) noexcept;
402
403} // namespace nix
Definition args.hh:29
Definition finally.hh:15
Definition logging.hh:67
Definition logging.hh:96
void writeStyledToStdout(std::string_view s)
Definition logging.cc:61
Definition configuration.hh:476
Definition fun.hh:19
This file defines two main structs/classes used in nix error handling.
File descriptor operations for almost arbitrary file descriptors.
int Descriptor
Definition file-descriptor.hh:36
std::string fmt(const std::string &s)
Definition fmt.hh:67
std::optional< nlohmann::json > parseJSONMessage(std::string_view msg, std::string_view source)
Definition logging.cc:440
void warn(const std::string &fs, const Args &... args)
Definition logging.hh:388
std::unique_ptr< Logger > makeTeeLogger(std::unique_ptr< Logger > mainLogger, std::vector< std::unique_ptr< Logger > > &&extraLoggers)
Definition tee-logger.cc:103
Logger * logger
Definition logging.cc:45
bool handleJSONLogMessage(const nlohmann::json &json, const Activity &act, std::map< ActivityId, Activity > &activities, std::string_view source, bool trusted)
Definition logging.cc:452
Definition logging.hh:221
Definition logging.hh:104
Definition logging.hh:134