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