1 // Copyright 2012 The Chromium Authors
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
4
5 #ifndef BASE_LOGGING_H_
6 #define BASE_LOGGING_H_
7
8 #include <stddef.h>
9
10 #include <cassert>
11 #include <cstdint>
12 #include <sstream>
13 #include <string>
14 #include <string_view>
15
16 #include "base/base_export.h"
17 #include "base/compiler_specific.h"
18 #include "base/dcheck_is_on.h"
19 #include "base/files/file_path.h"
20 #include "base/functional/callback_forward.h"
21 #include "base/logging/log_severity.h"
22 #include "base/strings/utf_ostream_operators.h"
23 #include "build/build_config.h"
24 #include "build/chromeos_buildflags.h"
25
26 #if BUILDFLAG(IS_CHROMEOS)
27 #include <cstdio>
28
29 #include "base/memory/raw_ptr.h"
30 #endif
31
32 #if BUILDFLAG(IS_WIN)
33 #include "base/win/windows_types.h"
34 #endif
35
36 //
37 // Optional message capabilities
38 // -----------------------------
39 // Assertion failed messages and fatal errors are displayed in a dialog box
40 // before the application exits. However, running this UI creates a message
41 // loop, which causes application messages to be processed and potentially
42 // dispatched to existing application windows. Since the application is in a
43 // bad state when this assertion dialog is displayed, these messages may not
44 // get processed and hang the dialog, or the application might go crazy.
45 //
46 // Therefore, it can be beneficial to display the error dialog in a separate
47 // process from the main application. When the logging system needs to display
48 // a fatal error dialog box, it will look for a program called
49 // "DebugMessage.exe" in the same directory as the application executable. It
50 // will run this application with the message as the command line, and will
51 // not include the name of the application as is traditional for easier
52 // parsing.
53 //
54 // The code for DebugMessage.exe is only one line. In WinMain, do:
55 // MessageBox(NULL, GetCommandLineW(), L"Fatal Error", 0);
56 //
57 // If DebugMessage.exe is not found, the logging code will use a normal
58 // MessageBox, potentially causing the problems discussed above.
59
60 // Instructions
61 // ------------
62 //
63 // Make a bunch of macros for logging. The way to log things is to stream
64 // things to LOG(<a particular severity level>). E.g.,
65 //
66 // LOG(INFO) << "Found " << num_cookies << " cookies";
67 //
68 // You can also do conditional logging:
69 //
70 // LOG_IF(INFO, num_cookies > 10) << "Got lots of cookies";
71 //
72 // The CHECK(condition) macro is active in both debug and release builds and
73 // effectively performs a LOG(FATAL) which terminates the process and
74 // generates a crashdump unless a debugger is attached.
75 //
76 // There are also "debug mode" logging macros like the ones above:
77 //
78 // DLOG(INFO) << "Found cookies";
79 //
80 // DLOG_IF(INFO, num_cookies > 10) << "Got lots of cookies";
81 //
82 // All "debug mode" logging is compiled away to nothing for non-debug mode
83 // compiles. LOG_IF and development flags also work well together
84 // because the code can be compiled away sometimes.
85 //
86 // We also have
87 //
88 // LOG_ASSERT(assertion);
89 // DLOG_ASSERT(assertion);
90 //
91 // which is syntactic sugar for {,D}LOG_IF(FATAL, assert fails) << assertion;
92 //
93 // There are "verbose level" logging macros. They look like
94 //
95 // VLOG(1) << "I'm printed when you run the program with --v=1 or more";
96 // VLOG(2) << "I'm printed when you run the program with --v=2 or more";
97 //
98 // These always log at the INFO log level (when they log at all).
99 //
100 // The verbose logging can also be turned on module-by-module. For instance,
101 // --vmodule=profile=2,icon_loader=1,browser_*=3,*/chromeos/*=4 --v=0
102 // will cause:
103 // a. VLOG(2) and lower messages to be printed from profile.{h,cc}
104 // b. VLOG(1) and lower messages to be printed from icon_loader.{h,cc}
105 // c. VLOG(3) and lower messages to be printed from files prefixed with
106 // "browser"
107 // d. VLOG(4) and lower messages to be printed from files under a
108 // "chromeos" directory.
109 // e. VLOG(0) and lower messages to be printed from elsewhere
110 //
111 // The wildcarding functionality shown by (c) supports both '*' (match
112 // 0 or more characters) and '?' (match any single character)
113 // wildcards. Any pattern containing a forward or backward slash will
114 // be tested against the whole pathname and not just the module.
115 // E.g., "*/foo/bar/*=2" would change the logging level for all code
116 // in source files under a "foo/bar" directory.
117 //
118 // Note that for a Chromium binary built in release mode (is_debug = false) you
119 // must pass "--enable-logging=stderr" in order to see the output of VLOG
120 // statements.
121 //
122 // There's also VLOG_IS_ON(n) "verbose level" condition macro. To be used as
123 //
124 // if (VLOG_IS_ON(2)) {
125 // // do some logging preparation and logging
126 // // that can't be accomplished with just VLOG(2) << ...;
127 // }
128 //
129 // There is also a VLOG_IF "verbose level" condition macro for sample
130 // cases, when some extra computation and preparation for logs is not
131 // needed.
132 //
133 // VLOG_IF(1, (size > 1024))
134 // << "I'm printed when size is more than 1024 and when you run the "
135 // "program with --v=1 or more";
136 //
137 // We also override the standard 'assert' to use 'DLOG_ASSERT'.
138 //
139 // Lastly, there is:
140 //
141 // PLOG(ERROR) << "Couldn't do foo";
142 // DPLOG(ERROR) << "Couldn't do foo";
143 // PLOG_IF(ERROR, cond) << "Couldn't do foo";
144 // DPLOG_IF(ERROR, cond) << "Couldn't do foo";
145 // PCHECK(condition) << "Couldn't do foo";
146 // DPCHECK(condition) << "Couldn't do foo";
147 //
148 // which append the last system error to the message in string form (taken from
149 // GetLastError() on Windows and errno on POSIX).
150 //
151 // The supported severity levels for macros that allow you to specify one
152 // are (in increasing order of severity) INFO, WARNING, ERROR, and FATAL.
153 //
154 // Very important: logging a message at the FATAL severity level causes
155 // the program to terminate (after the message is logged).
156 //
157 // There is the special severity of DFATAL, which logs FATAL in DCHECK-enabled
158 // builds, ERROR in normal mode.
159 //
160 // Output is formatted as per the following example, except on Chrome OS.
161 // [3816:3877:0812/234555.406952:VERBOSE1:drm_device_handle.cc(90)] Succeeded
162 // authenticating /dev/dri/card0 in 0 ms with 1 attempt(s)
163 //
164 // The colon separated fields inside the brackets are as follows:
165 // 0. An optional Logfile prefix (not included in this example)
166 // 1. Process ID
167 // 2. Thread ID
168 // 3. The date/time of the log message, in MMDD/HHMMSS.Milliseconds format
169 // 4. The log level
170 // 5. The filename and line number where the log was instantiated
171 //
172 // Output for Chrome OS can be switched to syslog-like format. See
173 // InitWithSyslogPrefix() in logging_chromeos.cc for details.
174 //
175 // Note that the visibility can be changed by setting preferences in
176 // SetLogItems()
177 //
178 // Additional logging-related information can be found here:
179 // https://chromium.googlesource.com/chromium/src/+/main/docs/linux/debugging.md#Logging
180
181 namespace logging {
182
183 // A bitmask of potential logging destinations.
184 using LoggingDestination = uint32_t;
185 // Specifies where logs will be written. Multiple destinations can be specified
186 // with bitwise OR.
187 // Unless destination is LOG_NONE, all logs with severity ERROR and above will
188 // be written to stderr in addition to the specified destination.
189 // LOG_TO_FILE includes logging to externally-provided file handles.
190 enum : uint32_t {
191 LOG_NONE = 0,
192 LOG_TO_FILE = 1 << 0,
193 LOG_TO_SYSTEM_DEBUG_LOG = 1 << 1,
194 LOG_TO_STDERR = 1 << 2,
195
196 LOG_TO_ALL = LOG_TO_FILE | LOG_TO_SYSTEM_DEBUG_LOG | LOG_TO_STDERR,
197
198 // On Windows, use a file next to the exe.
199 // On POSIX platforms, where it may not even be possible to locate the
200 // executable on disk, use stderr.
201 // On Fuchsia, use the Fuchsia logging service.
202 #if BUILDFLAG(IS_FUCHSIA) || BUILDFLAG(IS_NACL)
203 LOG_DEFAULT = LOG_TO_SYSTEM_DEBUG_LOG,
204 #elif BUILDFLAG(IS_WIN)
205 LOG_DEFAULT = LOG_TO_FILE,
206 #elif BUILDFLAG(IS_POSIX)
207 LOG_DEFAULT = LOG_TO_SYSTEM_DEBUG_LOG | LOG_TO_STDERR,
208 #endif
209 };
210
211 // Indicates that the log file should be locked when being written to.
212 // Unless there is only one single-threaded process that is logging to
213 // the log file, the file should be locked during writes to make each
214 // log output atomic. Other writers will block.
215 //
216 // All processes writing to the log file must have their locking set for it to
217 // work properly. Defaults to LOCK_LOG_FILE.
218 enum LogLockingState { LOCK_LOG_FILE, DONT_LOCK_LOG_FILE };
219
220 // On startup, should we delete or append to an existing log file (if any)?
221 // Defaults to APPEND_TO_OLD_LOG_FILE.
222 enum OldFileDeletionState { DELETE_OLD_LOG_FILE, APPEND_TO_OLD_LOG_FILE };
223
224 #if BUILDFLAG(IS_CHROMEOS)
225 // Defines the log message prefix format to use.
226 // LOG_FORMAT_SYSLOG indicates syslog-like message prefixes.
227 // LOG_FORMAT_CHROME indicates the normal Chrome format.
228 enum class BASE_EXPORT LogFormat { LOG_FORMAT_CHROME, LOG_FORMAT_SYSLOG };
229 #endif
230
231 struct BASE_EXPORT LoggingSettings {
232 // Equivalent to logging destination enum, but allows for multiple
233 // destinations.
234 uint32_t logging_dest = LOG_DEFAULT;
235
236 // The four settings below have an effect only when LOG_TO_FILE is
237 // set in |logging_dest|.
238 base::FilePath::StringType log_file_path;
239 LogLockingState lock_log = LOCK_LOG_FILE;
240 OldFileDeletionState delete_old = APPEND_TO_OLD_LOG_FILE;
241 #if BUILDFLAG(IS_CHROMEOS)
242 // Contains an optional file that logs should be written to. If present,
243 // |log_file_path| will be ignored, and the logging system will take ownership
244 // of the FILE. If there's an error writing to this file, no fallback paths
245 // will be opened.
246 raw_ptr<FILE> log_file = nullptr;
247 // ChromeOS uses the syslog log format by default.
248 LogFormat log_format = LogFormat::LOG_FORMAT_SYSLOG;
249 #endif
250 #if BUILDFLAG(IS_WIN)
251 // Contains an optional file that logs should be written to. If present,
252 // `log_file_path` will be ignored, and the logging system will take ownership
253 // of the HANDLE. If there's an error writing to this file, no fallback paths
254 // will be opened.
255 HANDLE log_file = nullptr;
256 #endif
257 };
258
259 // Define different names for the BaseInitLoggingImpl() function depending on
260 // whether NDEBUG is defined or not so that we'll fail to link if someone tries
261 // to compile logging.cc with NDEBUG but includes logging.h without defining it,
262 // or vice versa.
263 #if defined(NDEBUG)
264 #define BaseInitLoggingImpl BaseInitLoggingImpl_built_with_NDEBUG
265 #else
266 #define BaseInitLoggingImpl BaseInitLoggingImpl_built_without_NDEBUG
267 #endif
268
269 // Implementation of the InitLogging() method declared below. We use a
270 // more-specific name so we can #define it above without affecting other code
271 // that has named stuff "InitLogging".
272 BASE_EXPORT bool BaseInitLoggingImpl(const LoggingSettings& settings);
273
274 // Sets the log file name and other global logging state. Calling this function
275 // is recommended, and is normally done at the beginning of application init.
276 // If you don't call it, all the flags will be initialized to their default
277 // values, and there is a race condition that may leak a critical section
278 // object if two threads try to do the first log at the same time.
279 // See the definition of the enums above for descriptions and default values.
280 //
281 // The default log file is initialized to "debug.log" in the application
282 // directory. You probably don't want this, especially since the program
283 // directory may not be writable on an enduser's system.
284 //
285 // This function may be called a second time to re-direct logging (e.g after
286 // loging in to a user partition), however it should never be called more than
287 // twice.
InitLogging(const LoggingSettings & settings)288 inline bool InitLogging(const LoggingSettings& settings) {
289 return BaseInitLoggingImpl(settings);
290 }
291
292 // Sets the log level. Anything at or above this level will be written to the
293 // log file/displayed to the user (if applicable). Anything below this level
294 // will be silently ignored. The log level defaults to 0 (everything is logged
295 // up to level INFO) if this function is not called.
296 // Note that log messages for VLOG(x) are logged at level -x, so setting
297 // the min log level to negative values enables verbose logging and conversely,
298 // setting the VLOG default level will set this min level to a negative number,
299 // effectively enabling all levels of logging.
300 BASE_EXPORT void SetMinLogLevel(int level);
301
302 // Gets the current log level.
303 BASE_EXPORT int GetMinLogLevel();
304
305 // Used by LOG_IS_ON to lazy-evaluate stream arguments.
306 BASE_EXPORT bool ShouldCreateLogMessage(int severity);
307
308 // Gets the VLOG default verbosity level.
309 BASE_EXPORT int GetVlogVerbosity();
310
311 // Note that |N| is the size *with* the null terminator.
312 BASE_EXPORT int GetVlogLevelHelper(const char* file_start, size_t N);
313
314 // Gets the current vlog level for the given file (usually taken from __FILE__).
315 template <size_t N>
GetVlogLevel(const char (& file)[N])316 int GetVlogLevel(const char (&file)[N]) {
317 return GetVlogLevelHelper(file, N);
318 }
319
320 // Sets the common items you want to be prepended to each log message.
321 // process and thread IDs default to off, the timestamp defaults to on.
322 // If this function is not called, logging defaults to writing the timestamp
323 // only.
324 BASE_EXPORT void SetLogItems(bool enable_process_id, bool enable_thread_id,
325 bool enable_timestamp, bool enable_tickcount);
326
327 // Sets an optional prefix to add to each log message. |prefix| is not copied
328 // and should be a raw string constant. |prefix| must only contain ASCII letters
329 // to avoid confusion with PIDs and timestamps. Pass null to remove the prefix.
330 // Logging defaults to no prefix.
331 BASE_EXPORT void SetLogPrefix(const char* prefix);
332
333 // Sets whether or not you'd like to see fatal debug messages popped up in
334 // a dialog box or not.
335 // Dialogs are not shown by default.
336 BASE_EXPORT void SetShowErrorDialogs(bool enable_dialogs);
337
338 // Registers an abort hook with absl that will crash the process similarly to a
339 // `CHECK` failure in case of a FATAL error in absl (e.g., any operation that
340 // would throw an exception).
341 BASE_EXPORT void RegisterAbslAbortHook();
342
343 // Sets the Log Assert Handler that will be used to notify of check failures.
344 // Resets Log Assert Handler on object destruction.
345 // The default handler shows a dialog box and then terminate the process,
346 // however clients can use this function to override with their own handling
347 // (e.g. a silent one for Unit Tests)
348 using LogAssertHandlerFunction =
349 base::RepeatingCallback<void(const char* file,
350 int line,
351 std::string_view message,
352 std::string_view stack_trace)>;
353
354 class BASE_EXPORT ScopedLogAssertHandler {
355 public:
356 explicit ScopedLogAssertHandler(LogAssertHandlerFunction handler);
357 ScopedLogAssertHandler(const ScopedLogAssertHandler&) = delete;
358 ScopedLogAssertHandler& operator=(const ScopedLogAssertHandler&) = delete;
359 ~ScopedLogAssertHandler();
360 };
361
362 // Sets the Log Message Handler that gets passed every log message before
363 // it's sent to other log destinations (if any).
364 // Returns true to signal that it handled the message and the message
365 // should not be sent to other log destinations.
366 typedef bool (*LogMessageHandlerFunction)(int severity,
367 const char* file, int line, size_t message_start, const std::string& str);
368 BASE_EXPORT void SetLogMessageHandler(LogMessageHandlerFunction handler);
369 BASE_EXPORT LogMessageHandlerFunction GetLogMessageHandler();
370
371 // A few definitions of macros that don't generate much code. These are used
372 // by LOG() and LOG_IF, etc. Since these are used all over our code, it's
373 // better to have compact code for these operations.
374 #define COMPACT_GOOGLE_LOG_EX_INFO(ClassName, ...) \
375 ::logging::ClassName(__FILE__, __LINE__, ::logging::LOGGING_INFO, \
376 ##__VA_ARGS__)
377 #define COMPACT_GOOGLE_LOG_EX_WARNING(ClassName, ...) \
378 ::logging::ClassName(__FILE__, __LINE__, ::logging::LOGGING_WARNING, \
379 ##__VA_ARGS__)
380 #define COMPACT_GOOGLE_LOG_EX_ERROR(ClassName, ...) \
381 ::logging::ClassName(__FILE__, __LINE__, ::logging::LOGGING_ERROR, \
382 ##__VA_ARGS__)
383 #define COMPACT_GOOGLE_LOG_EX_FATAL(ClassName, ...) \
384 ::logging::ClassName##Fatal(__FILE__, __LINE__, ::logging::LOGGING_FATAL, \
385 ##__VA_ARGS__)
386 #define COMPACT_GOOGLE_LOG_EX_DFATAL(ClassName, ...) \
387 ::logging::ClassName(__FILE__, __LINE__, ::logging::LOGGING_DFATAL, \
388 ##__VA_ARGS__)
389
390 #define COMPACT_GOOGLE_LOG_INFO COMPACT_GOOGLE_LOG_EX_INFO(LogMessage)
391 #define COMPACT_GOOGLE_LOG_WARNING COMPACT_GOOGLE_LOG_EX_WARNING(LogMessage)
392 #define COMPACT_GOOGLE_LOG_ERROR COMPACT_GOOGLE_LOG_EX_ERROR(LogMessage)
393 #define COMPACT_GOOGLE_LOG_FATAL COMPACT_GOOGLE_LOG_EX_FATAL(LogMessage)
394 #define COMPACT_GOOGLE_LOG_DFATAL COMPACT_GOOGLE_LOG_EX_DFATAL(LogMessage)
395
396 #if BUILDFLAG(IS_WIN)
397 // wingdi.h defines ERROR to be 0. When we call LOG(ERROR), it gets
398 // substituted with 0, and it expands to COMPACT_GOOGLE_LOG_0. To allow us
399 // to keep using this syntax, we define this macro to do the same thing
400 // as COMPACT_GOOGLE_LOG_ERROR, and also define ERROR the same way that
401 // the Windows SDK does for consistency.
402 #define ERROR 0
403 #define COMPACT_GOOGLE_LOG_EX_0(ClassName, ...) \
404 COMPACT_GOOGLE_LOG_EX_ERROR(ClassName , ##__VA_ARGS__)
405 #define COMPACT_GOOGLE_LOG_0 COMPACT_GOOGLE_LOG_ERROR
406 // Needed for LOG_IS_ON(ERROR).
407 constexpr LogSeverity LOGGING_0 = LOGGING_ERROR;
408 #endif
409
410 // As special cases, we can assume that LOG_IS_ON(FATAL) always holds. Also,
411 // LOG_IS_ON(DFATAL) always holds in debug mode. In particular, CHECK()s will
412 // always fire if they fail.
413 // FATAL is always enabled and required to be resolved in compile time for
414 // LOG(FATAL) to be properly understood as [[noreturn]].
415 #define LOG_IS_ON(severity) \
416 (::logging::LOGGING_##severity == ::logging::LOGGING_FATAL || \
417 ::logging::ShouldCreateLogMessage(::logging::LOGGING_##severity))
418
419 // Define a default ENABLED_VLOG_LEVEL if it is not defined. The macros allows
420 // code to enable vlog level at build time without the need of --vmodule
421 // switch at runtime. This is intended for VLOGs that needed from production
422 // code without the cpu overhead to match vmodule patterns on every VLOG
423 // instance.
424 #if !defined(ENABLED_VLOG_LEVEL)
425 #define ENABLED_VLOG_LEVEL -1
426 #endif // !defined(ENABLED_VLOG_LEVEL)
427
428 // We don't do any caching tricks with VLOG_IS_ON() like the
429 // google-glog version since it increases binary size. This means
430 // that using the v-logging functions in conjunction with --vmodule
431 // may be slow.
432 #define VLOG_IS_ON(verboselevel) \
433 ((verboselevel) <= (ENABLED_VLOG_LEVEL) || \
434 (verboselevel) <= ::logging::GetVlogLevel(__FILE__))
435
436 // Helper macro which avoids evaluating the arguments to a stream if
437 // the condition doesn't hold. Condition is evaluated once and only once.
438 #define LAZY_STREAM(stream, condition) \
439 !(condition) ? (void) 0 : ::logging::LogMessageVoidify() & (stream)
440
441 // We use the preprocessor's merging operator, "##", so that, e.g.,
442 // LOG(INFO) becomes the token COMPACT_GOOGLE_LOG_INFO. There's some funny
443 // subtle difference between ostream member streaming functions (e.g.,
444 // ostream::operator<<(int) and ostream non-member streaming functions
445 // (e.g., ::operator<<(ostream&, string&): it turns out that it's
446 // impossible to stream something like a string directly to an unnamed
447 // ostream. We employ a neat hack by calling the stream() member
448 // function of LogMessage which seems to avoid the problem.
449 #define LOG_STREAM(severity) COMPACT_GOOGLE_LOG_ ## severity.stream()
450
451 #define LOG(severity) LAZY_STREAM(LOG_STREAM(severity), LOG_IS_ON(severity))
452 #define LOG_IF(severity, condition) \
453 LAZY_STREAM(LOG_STREAM(severity), LOG_IS_ON(severity) && (condition))
454
455 // The VLOG macros log with negative verbosities.
456 #define VLOG_STREAM(verbose_level) \
457 ::logging::LogMessage(__FILE__, __LINE__, -(verbose_level)).stream()
458
459 #define VLOG(verbose_level) \
460 LAZY_STREAM(VLOG_STREAM(verbose_level), VLOG_IS_ON(verbose_level))
461
462 #define VLOG_IF(verbose_level, condition) \
463 LAZY_STREAM(VLOG_STREAM(verbose_level), \
464 VLOG_IS_ON(verbose_level) && (condition))
465
466 #if BUILDFLAG(IS_WIN)
467 #define VPLOG_STREAM(verbose_level) \
468 ::logging::Win32ErrorLogMessage(__FILE__, __LINE__, -(verbose_level), \
469 ::logging::GetLastSystemErrorCode()).stream()
470 #elif BUILDFLAG(IS_POSIX) || BUILDFLAG(IS_FUCHSIA)
471 #define VPLOG_STREAM(verbose_level) \
472 ::logging::ErrnoLogMessage(__FILE__, __LINE__, -(verbose_level), \
473 ::logging::GetLastSystemErrorCode()).stream()
474 #endif
475
476 #define VPLOG(verbose_level) \
477 LAZY_STREAM(VPLOG_STREAM(verbose_level), VLOG_IS_ON(verbose_level))
478
479 #define VPLOG_IF(verbose_level, condition) \
480 LAZY_STREAM(VPLOG_STREAM(verbose_level), \
481 VLOG_IS_ON(verbose_level) && (condition))
482
483 // TODO(akalin): Add more VLOG variants, e.g. VPLOG.
484
485 #define LOG_ASSERT(condition) \
486 LOG_IF(FATAL, !(ANALYZER_ASSUME_TRUE(condition))) \
487 << "Assert failed: " #condition ". "
488
489 #if BUILDFLAG(IS_WIN)
490 #define PLOG_STREAM(severity) \
491 COMPACT_GOOGLE_LOG_EX_ ## severity(Win32ErrorLogMessage, \
492 ::logging::GetLastSystemErrorCode()).stream()
493 #elif BUILDFLAG(IS_POSIX) || BUILDFLAG(IS_FUCHSIA)
494 #define PLOG_STREAM(severity) \
495 COMPACT_GOOGLE_LOG_EX_ ## severity(ErrnoLogMessage, \
496 ::logging::GetLastSystemErrorCode()).stream()
497 #endif
498
499 #define PLOG(severity) \
500 LAZY_STREAM(PLOG_STREAM(severity), LOG_IS_ON(severity))
501
502 #define PLOG_IF(severity, condition) \
503 LAZY_STREAM(PLOG_STREAM(severity), LOG_IS_ON(severity) && (condition))
504
505 BASE_EXPORT extern std::ostream* g_swallow_stream;
506
507 // Note that g_swallow_stream is used instead of an arbitrary LOG() stream to
508 // avoid the creation of an object with a non-trivial destructor (LogMessage).
509 // On MSVC x86 (checked on 2015 Update 3), this causes a few additional
510 // pointless instructions to be emitted even at full optimization level, even
511 // though the : arm of the ternary operator is clearly never executed. Using a
512 // simpler object to be &'d with Voidify() avoids these extra instructions.
513 // Using a simpler POD object with a templated operator<< also works to avoid
514 // these instructions. However, this causes warnings on statically defined
515 // implementations of operator<<(std::ostream, ...) in some .cc files, because
516 // they become defined-but-unreferenced functions. A reinterpret_cast of 0 to an
517 // ostream* also is not suitable, because some compilers warn of undefined
518 // behavior.
519 #define EAT_STREAM_PARAMETERS \
520 true ? (void)0 \
521 : ::logging::LogMessageVoidify() & (*::logging::g_swallow_stream)
522
523 // Definitions for DLOG et al.
524
525 #if DCHECK_IS_ON()
526
527 // All of these definitions use DLOG_IS_ON() rather than define to their LOG()
528 // equivalents, as DLOG(FATAL) and friends can't be understood as [[noreturn]]
529 // but LOG(FATAL) is.
530 #define DLOG_IS_ON(severity) \
531 (::logging::ShouldCreateLogMessage(::logging::LOGGING_##severity))
532
533 #define DLOG(severity) LAZY_STREAM(LOG_STREAM(severity), DLOG_IS_ON(severity))
534 #define DLOG_IF(severity, condition) \
535 LAZY_STREAM(LOG_STREAM(severity), DLOG_IS_ON(severity) && (condition))
536 #define DPLOG(severity) LAZY_STREAM(PLOG_STREAM(severity), DLOG_IS_ON(severity))
537 #define DPLOG_IF(severity, condition) \
538 LAZY_STREAM(PLOG_STREAM(severity), DLOG_IS_ON(severity) && (condition))
539 #define DVLOG_IF(verboselevel, condition) VLOG_IF(verboselevel, condition)
540 #define DVPLOG_IF(verboselevel, condition) VPLOG_IF(verboselevel, condition)
541 #define DLOG_ASSERT(condition) \
542 DLOG_IF(FATAL, !(condition)) << "Assert failed: " #condition ". "
543
544 #else // DCHECK_IS_ON()
545
546 // If !DCHECK_IS_ON(), we want to avoid emitting any references to |condition|
547 // (which may reference a variable defined only if DCHECK_IS_ON()).
548 // Contrast this with DCHECK et al., which has different behavior.
549
550 #define DLOG_IS_ON(severity) false
551 #define DLOG(severity) EAT_STREAM_PARAMETERS
552 #define DLOG_IF(severity, condition) EAT_STREAM_PARAMETERS
553 #define DPLOG(severity) EAT_STREAM_PARAMETERS
554 #define DPLOG_IF(severity, condition) EAT_STREAM_PARAMETERS
555 #define DVLOG_IF(verboselevel, condition) EAT_STREAM_PARAMETERS
556 #define DVPLOG_IF(verboselevel, condition) EAT_STREAM_PARAMETERS
557 #define DLOG_ASSERT(condition) EAT_STREAM_PARAMETERS
558
559 #endif // DCHECK_IS_ON()
560
561 #define DVLOG(verboselevel) DVLOG_IF(verboselevel, true)
562 #define DVPLOG(verboselevel) DVPLOG_IF(verboselevel, true)
563
564 // Definitions for DCHECK et al.
565
566 // TODO(pbos): Move this to check.h. Probably find a better name. Maybe this
567 // means that we want LogSeverity in a separate file, but maybe we can just have
568 // this as a bool DCHECK_IS_FATAL.
569 #if BUILDFLAG(DCHECK_IS_CONFIGURABLE)
570 BASE_EXPORT extern LogSeverity LOGGING_DCHECK;
571 #else
572 constexpr LogSeverity LOGGING_DCHECK = LOGGING_FATAL;
573 #endif // BUILDFLAG(DCHECK_IS_CONFIGURABLE)
574
575 // Redefine the standard assert to use our nice log files
576 #undef assert
577 #define assert(x) DLOG_ASSERT(x)
578
579 // This class more or less represents a particular log message. You
580 // create an instance of LogMessage and then stream stuff to it.
581 // When you finish streaming to it, ~LogMessage is called and the
582 // full message gets streamed to the appropriate destination.
583 //
584 // You shouldn't actually use LogMessage's constructor to log things,
585 // though. You should use the LOG() macro (and variants thereof)
586 // above.
587 class BASE_EXPORT LogMessage {
588 public:
589 // Used for LOG(severity).
590 LogMessage(const char* file, int line, LogSeverity severity);
591
592 // Used for CHECK(). Implied severity = LOGGING_FATAL.
593 LogMessage(const char* file, int line, const char* condition);
594 LogMessage(const LogMessage&) = delete;
595 LogMessage& operator=(const LogMessage&) = delete;
596 virtual ~LogMessage();
597
stream()598 std::ostream& stream() { return stream_; }
599
severity()600 LogSeverity severity() const { return severity_; }
str()601 std::string str() const { return stream_.str(); }
file()602 const char* file() const { return file_; }
line()603 int line() const { return line_; }
604
605 // Gets file:line: message in a format suitable for crash reporting.
606 std::string BuildCrashString() const;
607
608 protected:
609 void Flush();
610
611 private:
612 void Init(const char* file, int line);
613
614 void HandleFatal(size_t stack_start, const std::string& str_newline) const;
615
616 const LogSeverity severity_;
617 std::ostringstream stream_;
618 size_t message_start_; // Offset of the start of the message (past prefix
619 // info).
620 // The file and line information passed in to the constructor.
621 const char* const file_;
622 const int line_;
623
624 #if BUILDFLAG(IS_CHROMEOS)
625 void InitWithSyslogPrefix(std::string_view filename,
626 int line,
627 uint64_t tick_count,
628 const char* log_severity_name_c_str,
629 const char* log_prefix,
630 bool enable_process_id,
631 bool enable_thread_id,
632 bool enable_timestamp,
633 bool enable_tickcount);
634 #endif
635 };
636
637 class BASE_EXPORT LogMessageFatal final : public LogMessage {
638 public:
639 using LogMessage::LogMessage;
640 [[noreturn]] ~LogMessageFatal() override;
641 };
642
643 // This class is used to explicitly ignore values in the conditional
644 // logging macros. This avoids compiler warnings like "value computed
645 // is not used" and "statement has no effect".
646 class LogMessageVoidify {
647 public:
648 LogMessageVoidify() = default;
649 // This has to be an operator with a precedence lower than << but
650 // higher than ?:
651 void operator&(std::ostream&) { }
652 };
653
654 #if BUILDFLAG(IS_WIN)
655 typedef unsigned long SystemErrorCode;
656 #elif BUILDFLAG(IS_POSIX) || BUILDFLAG(IS_FUCHSIA)
657 typedef int SystemErrorCode;
658 #endif
659
660 // Alias for ::GetLastError() on Windows and errno on POSIX. Avoids having to
661 // pull in windows.h just for GetLastError() and DWORD.
662 BASE_EXPORT SystemErrorCode GetLastSystemErrorCode();
663 BASE_EXPORT std::string SystemErrorCodeToString(SystemErrorCode error_code);
664
665 #if BUILDFLAG(IS_WIN)
666 // Appends a formatted system message of the GetLastError() type.
667 class BASE_EXPORT Win32ErrorLogMessage : public LogMessage {
668 public:
669 Win32ErrorLogMessage(const char* file,
670 int line,
671 LogSeverity severity,
672 SystemErrorCode err);
673 Win32ErrorLogMessage(const Win32ErrorLogMessage&) = delete;
674 Win32ErrorLogMessage& operator=(const Win32ErrorLogMessage&) = delete;
675 // Appends the error message before destructing the encapsulated class.
676 ~Win32ErrorLogMessage() override;
677
678 protected:
679 void AppendError();
680
681 private:
682 SystemErrorCode err_;
683 };
684
685 class BASE_EXPORT Win32ErrorLogMessageFatal final
686 : public Win32ErrorLogMessage {
687 public:
688 using Win32ErrorLogMessage::Win32ErrorLogMessage;
689 [[noreturn]] ~Win32ErrorLogMessageFatal() override;
690 };
691
692 #elif BUILDFLAG(IS_POSIX) || BUILDFLAG(IS_FUCHSIA)
693 // Appends a formatted system message of the errno type
694 class BASE_EXPORT ErrnoLogMessage : public LogMessage {
695 public:
696 ErrnoLogMessage(const char* file,
697 int line,
698 LogSeverity severity,
699 SystemErrorCode err);
700 ErrnoLogMessage(const ErrnoLogMessage&) = delete;
701 ErrnoLogMessage& operator=(const ErrnoLogMessage&) = delete;
702 // Appends the error message before destructing the encapsulated class.
703 ~ErrnoLogMessage() override;
704
705 protected:
706 void AppendError();
707
708 private:
709 SystemErrorCode err_;
710 };
711
712 class BASE_EXPORT ErrnoLogMessageFatal final : public ErrnoLogMessage {
713 public:
714 using ErrnoLogMessage::ErrnoLogMessage;
715 [[noreturn]] ~ErrnoLogMessageFatal() override;
716 };
717
718 #endif // BUILDFLAG(IS_WIN)
719
720 // Closes the log file explicitly if open.
721 // NOTE: Since the log file is opened as necessary by the action of logging
722 // statements, there's no guarantee that it will stay closed
723 // after this call.
724 BASE_EXPORT void CloseLogFile();
725
726 #if BUILDFLAG(IS_CHROMEOS_ASH)
727 // Returns a new file handle that will write to the same destination as the
728 // currently open log file. Returns nullptr if logging to a file is disabled,
729 // or if opening the file failed. This is intended to be used to initialize
730 // logging in child processes that are unable to open files.
731 BASE_EXPORT FILE* DuplicateLogFILE();
732 #endif
733
734 // Async signal safe logging mechanism.
735 BASE_EXPORT void RawLog(int level, const char* message);
736
737 #define RAW_LOG(level, message) \
738 ::logging::RawLog(::logging::LOGGING_##level, message)
739
740 #if BUILDFLAG(IS_WIN)
741 // Returns true if logging to file is enabled.
742 BASE_EXPORT bool IsLoggingToFileEnabled();
743
744 // Returns the default log file path.
745 BASE_EXPORT std::wstring GetLogFileFullPath();
746
747 // Duplicates the log file handle to send into a child process.
748 BASE_EXPORT HANDLE DuplicateLogFileHandle();
749 #endif
750
751 } // namespace logging
752
753 #endif // BASE_LOGGING_H_
754