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