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