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/memory/raw_ptr.h"
22 #include "base/scoped_clear_last_error.h"
23 #include "base/strings/string_piece.h"
24 #include "base/strings/utf_ostream_operators.h"
25 #include "build/build_config.h"
26 #include "build/chromeos_buildflags.h"
27
28 #if BUILDFLAG(IS_CHROMEOS)
29 #include <cstdio>
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 // Sets the Log Assert Handler that will be used to notify of check failures.
339 // Resets Log Assert Handler on object destruction.
340 // The default handler shows a dialog box and then terminate the process,
341 // however clients can use this function to override with their own handling
342 // (e.g. a silent one for Unit Tests)
343 using LogAssertHandlerFunction =
344 base::RepeatingCallback<void(const char* file,
345 int line,
346 const base::StringPiece message,
347 const base::StringPiece stack_trace)>;
348
349 class BASE_EXPORT ScopedLogAssertHandler {
350 public:
351 explicit ScopedLogAssertHandler(LogAssertHandlerFunction handler);
352 ScopedLogAssertHandler(const ScopedLogAssertHandler&) = delete;
353 ScopedLogAssertHandler& operator=(const ScopedLogAssertHandler&) = delete;
354 ~ScopedLogAssertHandler();
355 };
356
357 // Sets the Log Message Handler that gets passed every log message before
358 // it's sent to other log destinations (if any).
359 // Returns true to signal that it handled the message and the message
360 // should not be sent to other log destinations.
361 typedef bool (*LogMessageHandlerFunction)(int severity,
362 const char* file, int line, size_t message_start, const std::string& str);
363 BASE_EXPORT void SetLogMessageHandler(LogMessageHandlerFunction handler);
364 BASE_EXPORT LogMessageHandlerFunction GetLogMessageHandler();
365
366 using LogSeverity = int;
367 constexpr LogSeverity LOGGING_VERBOSE = -1; // This is level 1 verbosity
368 // Note: the log severities are used to index into the array of names,
369 // see log_severity_names.
370 constexpr LogSeverity LOGGING_INFO = 0;
371 constexpr LogSeverity LOGGING_WARNING = 1;
372 constexpr LogSeverity LOGGING_ERROR = 2;
373 constexpr LogSeverity LOGGING_FATAL = 3;
374 constexpr LogSeverity LOGGING_NUM_SEVERITIES = 4;
375
376 // LOGGING_DFATAL is LOGGING_FATAL in DCHECK-enabled builds, ERROR in normal
377 // mode.
378 #if DCHECK_IS_ON()
379 constexpr LogSeverity LOGGING_DFATAL = LOGGING_FATAL;
380 #else
381 constexpr LogSeverity LOGGING_DFATAL = LOGGING_ERROR;
382 #endif
383
384 // A few definitions of macros that don't generate much code. These are used
385 // by LOG() and LOG_IF, etc. Since these are used all over our code, it's
386 // better to have compact code for these operations.
387 #define COMPACT_GOOGLE_LOG_EX_INFO(ClassName, ...) \
388 ::logging::ClassName(__FILE__, __LINE__, ::logging::LOGGING_INFO, \
389 ##__VA_ARGS__)
390 #define COMPACT_GOOGLE_LOG_EX_WARNING(ClassName, ...) \
391 ::logging::ClassName(__FILE__, __LINE__, ::logging::LOGGING_WARNING, \
392 ##__VA_ARGS__)
393 #define COMPACT_GOOGLE_LOG_EX_ERROR(ClassName, ...) \
394 ::logging::ClassName(__FILE__, __LINE__, ::logging::LOGGING_ERROR, \
395 ##__VA_ARGS__)
396 #define COMPACT_GOOGLE_LOG_EX_FATAL(ClassName, ...) \
397 ::logging::ClassName##Fatal(__FILE__, __LINE__, ::logging::LOGGING_FATAL, \
398 ##__VA_ARGS__)
399 #define COMPACT_GOOGLE_LOG_EX_DFATAL(ClassName, ...) \
400 ::logging::ClassName(__FILE__, __LINE__, ::logging::LOGGING_DFATAL, \
401 ##__VA_ARGS__)
402
403 #define COMPACT_GOOGLE_LOG_INFO COMPACT_GOOGLE_LOG_EX_INFO(LogMessage)
404 #define COMPACT_GOOGLE_LOG_WARNING COMPACT_GOOGLE_LOG_EX_WARNING(LogMessage)
405 #define COMPACT_GOOGLE_LOG_ERROR COMPACT_GOOGLE_LOG_EX_ERROR(LogMessage)
406 #define COMPACT_GOOGLE_LOG_FATAL COMPACT_GOOGLE_LOG_EX_FATAL(LogMessage)
407 #define COMPACT_GOOGLE_LOG_DFATAL COMPACT_GOOGLE_LOG_EX_DFATAL(LogMessage)
408
409 #if BUILDFLAG(IS_WIN)
410 // wingdi.h defines ERROR to be 0. When we call LOG(ERROR), it gets
411 // substituted with 0, and it expands to COMPACT_GOOGLE_LOG_0. To allow us
412 // to keep using this syntax, we define this macro to do the same thing
413 // as COMPACT_GOOGLE_LOG_ERROR, and also define ERROR the same way that
414 // the Windows SDK does for consistency.
415 #define ERROR 0
416 #define COMPACT_GOOGLE_LOG_EX_0(ClassName, ...) \
417 COMPACT_GOOGLE_LOG_EX_ERROR(ClassName , ##__VA_ARGS__)
418 #define COMPACT_GOOGLE_LOG_0 COMPACT_GOOGLE_LOG_ERROR
419 // Needed for LOG_IS_ON(ERROR).
420 constexpr LogSeverity LOGGING_0 = LOGGING_ERROR;
421 #endif
422
423 // As special cases, we can assume that LOG_IS_ON(FATAL) always holds. Also,
424 // LOG_IS_ON(DFATAL) always holds in debug mode. In particular, CHECK()s will
425 // always fire if they fail.
426 // FATAL is always enabled and required to be resolved in compile time for
427 // LOG(FATAL) to be properly understood as [[noreturn]].
428 #define LOG_IS_ON(severity) \
429 (::logging::LOGGING_##severity == ::logging::LOGGING_FATAL || \
430 ::logging::ShouldCreateLogMessage(::logging::LOGGING_##severity))
431
432 // Define a default ENABLED_VLOG_LEVEL if it is not defined. The macros allows
433 // code to enable vlog level at build time without the need of --vmodule
434 // switch at runtime. This is intended for VLOGs that needed from production
435 // code without the cpu overhead to match vmodule patterns on every VLOG
436 // instance.
437 #if !defined(ENABLED_VLOG_LEVEL)
438 #define ENABLED_VLOG_LEVEL -1
439 #endif // !defined(ENABLED_VLOG_LEVEL)
440
441 // We don't do any caching tricks with VLOG_IS_ON() like the
442 // google-glog version since it increases binary size. This means
443 // that using the v-logging functions in conjunction with --vmodule
444 // may be slow.
445 #define VLOG_IS_ON(verboselevel) \
446 ((verboselevel) <= (ENABLED_VLOG_LEVEL) || \
447 (verboselevel) <= ::logging::GetVlogLevel(__FILE__))
448
449 // Helper macro which avoids evaluating the arguments to a stream if
450 // the condition doesn't hold. Condition is evaluated once and only once.
451 #define LAZY_STREAM(stream, condition) \
452 !(condition) ? (void) 0 : ::logging::LogMessageVoidify() & (stream)
453
454 // We use the preprocessor's merging operator, "##", so that, e.g.,
455 // LOG(INFO) becomes the token COMPACT_GOOGLE_LOG_INFO. There's some funny
456 // subtle difference between ostream member streaming functions (e.g.,
457 // ostream::operator<<(int) and ostream non-member streaming functions
458 // (e.g., ::operator<<(ostream&, string&): it turns out that it's
459 // impossible to stream something like a string directly to an unnamed
460 // ostream. We employ a neat hack by calling the stream() member
461 // function of LogMessage which seems to avoid the problem.
462 #define LOG_STREAM(severity) COMPACT_GOOGLE_LOG_ ## severity.stream()
463
464 #define LOG(severity) LAZY_STREAM(LOG_STREAM(severity), LOG_IS_ON(severity))
465 #define LOG_IF(severity, condition) \
466 LAZY_STREAM(LOG_STREAM(severity), LOG_IS_ON(severity) && (condition))
467
468 // The VLOG macros log with negative verbosities.
469 #define VLOG_STREAM(verbose_level) \
470 ::logging::LogMessage(__FILE__, __LINE__, -(verbose_level)).stream()
471
472 #define VLOG(verbose_level) \
473 LAZY_STREAM(VLOG_STREAM(verbose_level), VLOG_IS_ON(verbose_level))
474
475 #define VLOG_IF(verbose_level, condition) \
476 LAZY_STREAM(VLOG_STREAM(verbose_level), \
477 VLOG_IS_ON(verbose_level) && (condition))
478
479 #if BUILDFLAG(IS_WIN)
480 #define VPLOG_STREAM(verbose_level) \
481 ::logging::Win32ErrorLogMessage(__FILE__, __LINE__, -(verbose_level), \
482 ::logging::GetLastSystemErrorCode()).stream()
483 #elif BUILDFLAG(IS_POSIX) || BUILDFLAG(IS_FUCHSIA)
484 #define VPLOG_STREAM(verbose_level) \
485 ::logging::ErrnoLogMessage(__FILE__, __LINE__, -(verbose_level), \
486 ::logging::GetLastSystemErrorCode()).stream()
487 #endif
488
489 #define VPLOG(verbose_level) \
490 LAZY_STREAM(VPLOG_STREAM(verbose_level), VLOG_IS_ON(verbose_level))
491
492 #define VPLOG_IF(verbose_level, condition) \
493 LAZY_STREAM(VPLOG_STREAM(verbose_level), \
494 VLOG_IS_ON(verbose_level) && (condition))
495
496 // TODO(akalin): Add more VLOG variants, e.g. VPLOG.
497
498 #define LOG_ASSERT(condition) \
499 LOG_IF(FATAL, !(ANALYZER_ASSUME_TRUE(condition))) \
500 << "Assert failed: " #condition ". "
501
502 #if BUILDFLAG(IS_WIN)
503 #define PLOG_STREAM(severity) \
504 COMPACT_GOOGLE_LOG_EX_ ## severity(Win32ErrorLogMessage, \
505 ::logging::GetLastSystemErrorCode()).stream()
506 #elif BUILDFLAG(IS_POSIX) || BUILDFLAG(IS_FUCHSIA)
507 #define PLOG_STREAM(severity) \
508 COMPACT_GOOGLE_LOG_EX_ ## severity(ErrnoLogMessage, \
509 ::logging::GetLastSystemErrorCode()).stream()
510 #endif
511
512 #define PLOG(severity) \
513 LAZY_STREAM(PLOG_STREAM(severity), LOG_IS_ON(severity))
514
515 #define PLOG_IF(severity, condition) \
516 LAZY_STREAM(PLOG_STREAM(severity), LOG_IS_ON(severity) && (condition))
517
518 BASE_EXPORT extern std::ostream* g_swallow_stream;
519
520 // Note that g_swallow_stream is used instead of an arbitrary LOG() stream to
521 // avoid the creation of an object with a non-trivial destructor (LogMessage).
522 // On MSVC x86 (checked on 2015 Update 3), this causes a few additional
523 // pointless instructions to be emitted even at full optimization level, even
524 // though the : arm of the ternary operator is clearly never executed. Using a
525 // simpler object to be &'d with Voidify() avoids these extra instructions.
526 // Using a simpler POD object with a templated operator<< also works to avoid
527 // these instructions. However, this causes warnings on statically defined
528 // implementations of operator<<(std::ostream, ...) in some .cc files, because
529 // they become defined-but-unreferenced functions. A reinterpret_cast of 0 to an
530 // ostream* also is not suitable, because some compilers warn of undefined
531 // behavior.
532 #define EAT_STREAM_PARAMETERS \
533 true ? (void)0 \
534 : ::logging::LogMessageVoidify() & (*::logging::g_swallow_stream)
535
536 // Definitions for DLOG et al.
537
538 #if DCHECK_IS_ON()
539
540 // All of these definitions use DLOG_IS_ON() rather than define to their LOG()
541 // equivalents, as DLOG(FATAL) and friends can't be understood as [[noreturn]]
542 // but LOG(FATAL) is.
543 #define DLOG_IS_ON(severity) \
544 (::logging::ShouldCreateLogMessage(::logging::LOGGING_##severity))
545
546 #define DLOG(severity) LAZY_STREAM(LOG_STREAM(severity), DLOG_IS_ON(severity))
547 #define DLOG_IF(severity, condition) \
548 LAZY_STREAM(LOG_STREAM(severity), DLOG_IS_ON(severity) && (condition))
549 #define DPLOG(severity) LAZY_STREAM(PLOG_STREAM(severity), DLOG_IS_ON(severity))
550 #define DPLOG_IF(severity, condition) \
551 LAZY_STREAM(PLOG_STREAM(severity), DLOG_IS_ON(severity) && (condition))
552 #define DVLOG_IF(verboselevel, condition) VLOG_IF(verboselevel, condition)
553 #define DVPLOG_IF(verboselevel, condition) VPLOG_IF(verboselevel, condition)
554 #define DLOG_ASSERT(condition) \
555 DLOG_IF(FATAL, !(condition)) << "Assert failed: " #condition ". "
556
557 #else // DCHECK_IS_ON()
558
559 // If !DCHECK_IS_ON(), we want to avoid emitting any references to |condition|
560 // (which may reference a variable defined only if DCHECK_IS_ON()).
561 // Contrast this with DCHECK et al., which has different behavior.
562
563 #define DLOG_IS_ON(severity) false
564 #define DLOG(severity) EAT_STREAM_PARAMETERS
565 #define DLOG_IF(severity, condition) EAT_STREAM_PARAMETERS
566 #define DPLOG(severity) EAT_STREAM_PARAMETERS
567 #define DPLOG_IF(severity, condition) EAT_STREAM_PARAMETERS
568 #define DVLOG_IF(verboselevel, condition) EAT_STREAM_PARAMETERS
569 #define DVPLOG_IF(verboselevel, condition) EAT_STREAM_PARAMETERS
570 #define DLOG_ASSERT(condition) EAT_STREAM_PARAMETERS
571
572 #endif // DCHECK_IS_ON()
573
574 #define DVLOG(verboselevel) DVLOG_IF(verboselevel, true)
575 #define DVPLOG(verboselevel) DVPLOG_IF(verboselevel, true)
576
577 // Definitions for DCHECK et al.
578
579 // TODO(pbos): Move this to check.h. Probably find a better name. Maybe this
580 // means that we want LogSeverity in a separate file, but maybe we can just have
581 // this as a bool DCHECK_IS_FATAL.
582 #if BUILDFLAG(DCHECK_IS_CONFIGURABLE)
583 BASE_EXPORT extern LogSeverity LOGGING_DCHECK;
584 #else
585 constexpr LogSeverity LOGGING_DCHECK = LOGGING_FATAL;
586 #endif // BUILDFLAG(DCHECK_IS_CONFIGURABLE)
587
588 // Redefine the standard assert to use our nice log files
589 #undef assert
590 #define assert(x) DLOG_ASSERT(x)
591
592 // This class more or less represents a particular log message. You
593 // create an instance of LogMessage and then stream stuff to it.
594 // When you finish streaming to it, ~LogMessage is called and the
595 // full message gets streamed to the appropriate destination.
596 //
597 // You shouldn't actually use LogMessage's constructor to log things,
598 // though. You should use the LOG() macro (and variants thereof)
599 // above.
600 class BASE_EXPORT LogMessage {
601 public:
602 // Used for LOG(severity).
603 LogMessage(const char* file, int line, LogSeverity severity);
604
605 // Used for CHECK(). Implied severity = LOGGING_FATAL.
606 LogMessage(const char* file, int line, const char* condition);
607 LogMessage(const LogMessage&) = delete;
608 LogMessage& operator=(const LogMessage&) = delete;
609 virtual ~LogMessage();
610
stream()611 std::ostream& stream() { return stream_; }
612
severity()613 LogSeverity severity() const { return severity_; }
str()614 std::string str() const { return stream_.str(); }
file()615 const char* file() const { return file_; }
line()616 int line() const { return line_; }
617
618 // Gets file:line: message in a format suitable for crash reporting.
619 std::string BuildCrashString() const;
620
621 protected:
622 void Flush();
623
624 private:
625 void Init(const char* file, int line);
626
627 void HandleFatal(size_t stack_start, const std::string& str_newline) const;
628
629 const LogSeverity severity_;
630 std::ostringstream stream_;
631 size_t message_start_; // Offset of the start of the message (past prefix
632 // info).
633 // The file and line information passed in to the constructor.
634 const char* const file_;
635 const int line_;
636
637 // This is useful since the LogMessage class uses a lot of Win32 calls
638 // that will lose the value of GLE and the code that called the log function
639 // will have lost the thread error value when the log call returns.
640 base::ScopedClearLastError last_error_;
641
642 #if BUILDFLAG(IS_CHROMEOS)
643 void InitWithSyslogPrefix(base::StringPiece filename,
644 int line,
645 uint64_t tick_count,
646 const char* log_severity_name_c_str,
647 const char* log_prefix,
648 bool enable_process_id,
649 bool enable_thread_id,
650 bool enable_timestamp,
651 bool enable_tickcount);
652 #endif
653 };
654
655 class BASE_EXPORT LogMessageFatal final : public LogMessage {
656 public:
657 using LogMessage::LogMessage;
658 [[noreturn]] ~LogMessageFatal() override;
659 };
660
661 // This class is used to explicitly ignore values in the conditional
662 // logging macros. This avoids compiler warnings like "value computed
663 // is not used" and "statement has no effect".
664 class LogMessageVoidify {
665 public:
666 LogMessageVoidify() = default;
667 // This has to be an operator with a precedence lower than << but
668 // higher than ?:
669 void operator&(std::ostream&) { }
670 };
671
672 #if BUILDFLAG(IS_WIN)
673 typedef unsigned long SystemErrorCode;
674 #elif BUILDFLAG(IS_POSIX) || BUILDFLAG(IS_FUCHSIA)
675 typedef int SystemErrorCode;
676 #endif
677
678 // Alias for ::GetLastError() on Windows and errno on POSIX. Avoids having to
679 // pull in windows.h just for GetLastError() and DWORD.
680 BASE_EXPORT SystemErrorCode GetLastSystemErrorCode();
681 BASE_EXPORT std::string SystemErrorCodeToString(SystemErrorCode error_code);
682
683 #if BUILDFLAG(IS_WIN)
684 // Appends a formatted system message of the GetLastError() type.
685 class BASE_EXPORT Win32ErrorLogMessage : public LogMessage {
686 public:
687 Win32ErrorLogMessage(const char* file,
688 int line,
689 LogSeverity severity,
690 SystemErrorCode err);
691 Win32ErrorLogMessage(const Win32ErrorLogMessage&) = delete;
692 Win32ErrorLogMessage& operator=(const Win32ErrorLogMessage&) = delete;
693 // Appends the error message before destructing the encapsulated class.
694 ~Win32ErrorLogMessage() override;
695
696 protected:
697 void AppendError();
698
699 private:
700 SystemErrorCode err_;
701 };
702
703 class BASE_EXPORT Win32ErrorLogMessageFatal final
704 : public Win32ErrorLogMessage {
705 public:
706 using Win32ErrorLogMessage::Win32ErrorLogMessage;
707 [[noreturn]] ~Win32ErrorLogMessageFatal() override;
708 };
709
710 #elif BUILDFLAG(IS_POSIX) || BUILDFLAG(IS_FUCHSIA)
711 // Appends a formatted system message of the errno type
712 class BASE_EXPORT ErrnoLogMessage : public LogMessage {
713 public:
714 ErrnoLogMessage(const char* file,
715 int line,
716 LogSeverity severity,
717 SystemErrorCode err);
718 ErrnoLogMessage(const ErrnoLogMessage&) = delete;
719 ErrnoLogMessage& operator=(const ErrnoLogMessage&) = delete;
720 // Appends the error message before destructing the encapsulated class.
721 ~ErrnoLogMessage() override;
722
723 protected:
724 void AppendError();
725
726 private:
727 SystemErrorCode err_;
728 };
729
730 class BASE_EXPORT ErrnoLogMessageFatal final : public ErrnoLogMessage {
731 public:
732 using ErrnoLogMessage::ErrnoLogMessage;
733 [[noreturn]] ~ErrnoLogMessageFatal() override;
734 };
735
736 #endif // BUILDFLAG(IS_WIN)
737
738 // Closes the log file explicitly if open.
739 // NOTE: Since the log file is opened as necessary by the action of logging
740 // statements, there's no guarantee that it will stay closed
741 // after this call.
742 BASE_EXPORT void CloseLogFile();
743
744 #if BUILDFLAG(IS_CHROMEOS_ASH)
745 // Returns a new file handle that will write to the same destination as the
746 // currently open log file. Returns nullptr if logging to a file is disabled,
747 // or if opening the file failed. This is intended to be used to initialize
748 // logging in child processes that are unable to open files.
749 BASE_EXPORT FILE* DuplicateLogFILE();
750 #endif
751
752 // Async signal safe logging mechanism.
753 BASE_EXPORT void RawLog(int level, const char* message);
754
755 #define RAW_LOG(level, message) \
756 ::logging::RawLog(::logging::LOGGING_##level, message)
757
758 #if BUILDFLAG(IS_WIN)
759 // Returns true if logging to file is enabled.
760 BASE_EXPORT bool IsLoggingToFileEnabled();
761
762 // Returns the default log file path.
763 BASE_EXPORT std::wstring GetLogFileFullPath();
764
765 // Duplicates the log file handle to send into a child process.
766 BASE_EXPORT HANDLE DuplicateLogFileHandle();
767 #endif
768
769 } // namespace logging
770
771 #endif // BASE_LOGGING_H_
772