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