Revert 249576 "Cast: Wiring up the asyc initialization with the ..."
[chromium-blink-merge.git] / base / logging.h
blob014078023e6f572f9472d8b7653899ea1de99a1c
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.
5 #ifndef BASE_LOGGING_H_
6 #define BASE_LOGGING_H_
8 #include <cassert>
9 #include <string>
10 #include <cstring>
11 #include <sstream>
13 #include "base/base_export.h"
14 #include "base/basictypes.h"
15 #include "base/debug/debugger.h"
16 #include "build/build_config.h"
19 // Optional message capabilities
20 // -----------------------------
21 // Assertion failed messages and fatal errors are displayed in a dialog box
22 // before the application exits. However, running this UI creates a message
23 // loop, which causes application messages to be processed and potentially
24 // dispatched to existing application windows. Since the application is in a
25 // bad state when this assertion dialog is displayed, these messages may not
26 // get processed and hang the dialog, or the application might go crazy.
28 // Therefore, it can be beneficial to display the error dialog in a separate
29 // process from the main application. When the logging system needs to display
30 // a fatal error dialog box, it will look for a program called
31 // "DebugMessage.exe" in the same directory as the application executable. It
32 // will run this application with the message as the command line, and will
33 // not include the name of the application as is traditional for easier
34 // parsing.
36 // The code for DebugMessage.exe is only one line. In WinMain, do:
37 // MessageBox(NULL, GetCommandLineW(), L"Fatal Error", 0);
39 // If DebugMessage.exe is not found, the logging code will use a normal
40 // MessageBox, potentially causing the problems discussed above.
43 // Instructions
44 // ------------
46 // Make a bunch of macros for logging. The way to log things is to stream
47 // things to LOG(<a particular severity level>). E.g.,
49 // LOG(INFO) << "Found " << num_cookies << " cookies";
51 // You can also do conditional logging:
53 // LOG_IF(INFO, num_cookies > 10) << "Got lots of cookies";
55 // The CHECK(condition) macro is active in both debug and release builds and
56 // effectively performs a LOG(FATAL) which terminates the process and
57 // generates a crashdump unless a debugger is attached.
59 // There are also "debug mode" logging macros like the ones above:
61 // DLOG(INFO) << "Found cookies";
63 // DLOG_IF(INFO, num_cookies > 10) << "Got lots of cookies";
65 // All "debug mode" logging is compiled away to nothing for non-debug mode
66 // compiles. LOG_IF and development flags also work well together
67 // because the code can be compiled away sometimes.
69 // We also have
71 // LOG_ASSERT(assertion);
72 // DLOG_ASSERT(assertion);
74 // which is syntactic sugar for {,D}LOG_IF(FATAL, assert fails) << assertion;
76 // There are "verbose level" logging macros. They look like
78 // VLOG(1) << "I'm printed when you run the program with --v=1 or more";
79 // VLOG(2) << "I'm printed when you run the program with --v=2 or more";
81 // These always log at the INFO log level (when they log at all).
82 // The verbose logging can also be turned on module-by-module. For instance,
83 // --vmodule=profile=2,icon_loader=1,browser_*=3,*/chromeos/*=4 --v=0
84 // will cause:
85 // a. VLOG(2) and lower messages to be printed from profile.{h,cc}
86 // b. VLOG(1) and lower messages to be printed from icon_loader.{h,cc}
87 // c. VLOG(3) and lower messages to be printed from files prefixed with
88 // "browser"
89 // d. VLOG(4) and lower messages to be printed from files under a
90 // "chromeos" directory.
91 // e. VLOG(0) and lower messages to be printed from elsewhere
93 // The wildcarding functionality shown by (c) supports both '*' (match
94 // 0 or more characters) and '?' (match any single character)
95 // wildcards. Any pattern containing a forward or backward slash will
96 // be tested against the whole pathname and not just the module.
97 // E.g., "*/foo/bar/*=2" would change the logging level for all code
98 // in source files under a "foo/bar" directory.
100 // There's also VLOG_IS_ON(n) "verbose level" condition macro. To be used as
102 // if (VLOG_IS_ON(2)) {
103 // // do some logging preparation and logging
104 // // that can't be accomplished with just VLOG(2) << ...;
105 // }
107 // There is also a VLOG_IF "verbose level" condition macro for sample
108 // cases, when some extra computation and preparation for logs is not
109 // needed.
111 // VLOG_IF(1, (size > 1024))
112 // << "I'm printed when size is more than 1024 and when you run the "
113 // "program with --v=1 or more";
115 // We also override the standard 'assert' to use 'DLOG_ASSERT'.
117 // Lastly, there is:
119 // PLOG(ERROR) << "Couldn't do foo";
120 // DPLOG(ERROR) << "Couldn't do foo";
121 // PLOG_IF(ERROR, cond) << "Couldn't do foo";
122 // DPLOG_IF(ERROR, cond) << "Couldn't do foo";
123 // PCHECK(condition) << "Couldn't do foo";
124 // DPCHECK(condition) << "Couldn't do foo";
126 // which append the last system error to the message in string form (taken from
127 // GetLastError() on Windows and errno on POSIX).
129 // The supported severity levels for macros that allow you to specify one
130 // are (in increasing order of severity) INFO, WARNING, ERROR, ERROR_REPORT,
131 // and FATAL.
133 // Very important: logging a message at the FATAL severity level causes
134 // the program to terminate (after the message is logged).
136 // Note the special severity of ERROR_REPORT only available/relevant in normal
137 // mode, which displays error dialog without terminating the program. There is
138 // no error dialog for severity ERROR or below in normal mode.
140 // There is also the special severity of DFATAL, which logs FATAL in
141 // debug mode, ERROR in normal mode.
143 namespace logging {
145 // TODO(avi): do we want to do a unification of character types here?
146 #if defined(OS_WIN)
147 typedef wchar_t PathChar;
148 #else
149 typedef char PathChar;
150 #endif
152 // Where to record logging output? A flat file and/or system debug log
153 // via OutputDebugString.
154 enum LoggingDestination {
155 LOG_NONE = 0,
156 LOG_TO_FILE = 1 << 0,
157 LOG_TO_SYSTEM_DEBUG_LOG = 1 << 1,
159 LOG_TO_ALL = LOG_TO_FILE | LOG_TO_SYSTEM_DEBUG_LOG,
161 // On Windows, use a file next to the exe; on POSIX platforms, where
162 // it may not even be possible to locate the executable on disk, use
163 // stderr.
164 #if defined(OS_WIN)
165 LOG_DEFAULT = LOG_TO_FILE,
166 #elif defined(OS_POSIX)
167 LOG_DEFAULT = LOG_TO_SYSTEM_DEBUG_LOG,
168 #endif
171 // Indicates that the log file should be locked when being written to.
172 // Unless there is only one single-threaded process that is logging to
173 // the log file, the file should be locked during writes to make each
174 // log outut atomic. Other writers will block.
176 // All processes writing to the log file must have their locking set for it to
177 // work properly. Defaults to LOCK_LOG_FILE.
178 enum LogLockingState { LOCK_LOG_FILE, DONT_LOCK_LOG_FILE };
180 // On startup, should we delete or append to an existing log file (if any)?
181 // Defaults to APPEND_TO_OLD_LOG_FILE.
182 enum OldFileDeletionState { DELETE_OLD_LOG_FILE, APPEND_TO_OLD_LOG_FILE };
184 enum DcheckState {
185 DISABLE_DCHECK_FOR_NON_OFFICIAL_RELEASE_BUILDS,
186 ENABLE_DCHECK_FOR_NON_OFFICIAL_RELEASE_BUILDS
189 struct BASE_EXPORT LoggingSettings {
190 // The defaults values are:
192 // logging_dest: LOG_DEFAULT
193 // log_file: NULL
194 // lock_log: LOCK_LOG_FILE
195 // delete_old: APPEND_TO_OLD_LOG_FILE
196 // dcheck_state: DISABLE_DCHECK_FOR_NON_OFFICIAL_RELEASE_BUILDS
197 LoggingSettings();
199 LoggingDestination logging_dest;
201 // The three settings below have an effect only when LOG_TO_FILE is
202 // set in |logging_dest|.
203 const PathChar* log_file;
204 LogLockingState lock_log;
205 OldFileDeletionState delete_old;
207 DcheckState dcheck_state;
210 // Define different names for the BaseInitLoggingImpl() function depending on
211 // whether NDEBUG is defined or not so that we'll fail to link if someone tries
212 // to compile logging.cc with NDEBUG but includes logging.h without defining it,
213 // or vice versa.
214 #if NDEBUG
215 #define BaseInitLoggingImpl BaseInitLoggingImpl_built_with_NDEBUG
216 #else
217 #define BaseInitLoggingImpl BaseInitLoggingImpl_built_without_NDEBUG
218 #endif
220 // Implementation of the InitLogging() method declared below. We use a
221 // more-specific name so we can #define it above without affecting other code
222 // that has named stuff "InitLogging".
223 BASE_EXPORT bool BaseInitLoggingImpl(const LoggingSettings& settings);
225 // Sets the log file name and other global logging state. Calling this function
226 // is recommended, and is normally done at the beginning of application init.
227 // If you don't call it, all the flags will be initialized to their default
228 // values, and there is a race condition that may leak a critical section
229 // object if two threads try to do the first log at the same time.
230 // See the definition of the enums above for descriptions and default values.
232 // The default log file is initialized to "debug.log" in the application
233 // directory. You probably don't want this, especially since the program
234 // directory may not be writable on an enduser's system.
236 // This function may be called a second time to re-direct logging (e.g after
237 // loging in to a user partition), however it should never be called more than
238 // twice.
239 inline bool InitLogging(const LoggingSettings& settings) {
240 return BaseInitLoggingImpl(settings);
243 // Sets the log level. Anything at or above this level will be written to the
244 // log file/displayed to the user (if applicable). Anything below this level
245 // will be silently ignored. The log level defaults to 0 (everything is logged
246 // up to level INFO) if this function is not called.
247 // Note that log messages for VLOG(x) are logged at level -x, so setting
248 // the min log level to negative values enables verbose logging.
249 BASE_EXPORT void SetMinLogLevel(int level);
251 // Gets the current log level.
252 BASE_EXPORT int GetMinLogLevel();
254 // Gets the VLOG default verbosity level.
255 BASE_EXPORT int GetVlogVerbosity();
257 // Gets the current vlog level for the given file (usually taken from
258 // __FILE__).
260 // Note that |N| is the size *with* the null terminator.
261 BASE_EXPORT int GetVlogLevelHelper(const char* file_start, size_t N);
263 template <size_t N>
264 int GetVlogLevel(const char (&file)[N]) {
265 return GetVlogLevelHelper(file, N);
268 // Sets the common items you want to be prepended to each log message.
269 // process and thread IDs default to off, the timestamp defaults to on.
270 // If this function is not called, logging defaults to writing the timestamp
271 // only.
272 BASE_EXPORT void SetLogItems(bool enable_process_id, bool enable_thread_id,
273 bool enable_timestamp, bool enable_tickcount);
275 // Sets whether or not you'd like to see fatal debug messages popped up in
276 // a dialog box or not.
277 // Dialogs are not shown by default.
278 BASE_EXPORT void SetShowErrorDialogs(bool enable_dialogs);
280 // Sets the Log Assert Handler that will be used to notify of check failures.
281 // The default handler shows a dialog box and then terminate the process,
282 // however clients can use this function to override with their own handling
283 // (e.g. a silent one for Unit Tests)
284 typedef void (*LogAssertHandlerFunction)(const std::string& str);
285 BASE_EXPORT void SetLogAssertHandler(LogAssertHandlerFunction handler);
287 // Sets the Log Report Handler that will be used to notify of check failures
288 // in non-debug mode. The default handler shows a dialog box and continues
289 // the execution, however clients can use this function to override with their
290 // own handling.
291 typedef void (*LogReportHandlerFunction)(const std::string& str);
292 BASE_EXPORT void SetLogReportHandler(LogReportHandlerFunction handler);
294 // Sets the Log Message Handler that gets passed every log message before
295 // it's sent to other log destinations (if any).
296 // Returns true to signal that it handled the message and the message
297 // should not be sent to other log destinations.
298 typedef bool (*LogMessageHandlerFunction)(int severity,
299 const char* file, int line, size_t message_start, const std::string& str);
300 BASE_EXPORT void SetLogMessageHandler(LogMessageHandlerFunction handler);
301 BASE_EXPORT LogMessageHandlerFunction GetLogMessageHandler();
303 typedef int LogSeverity;
304 const LogSeverity LOG_VERBOSE = -1; // This is level 1 verbosity
305 // Note: the log severities are used to index into the array of names,
306 // see log_severity_names.
307 const LogSeverity LOG_INFO = 0;
308 const LogSeverity LOG_WARNING = 1;
309 const LogSeverity LOG_ERROR = 2;
310 const LogSeverity LOG_ERROR_REPORT = 3;
311 const LogSeverity LOG_FATAL = 4;
312 const LogSeverity LOG_NUM_SEVERITIES = 5;
314 // LOG_DFATAL is LOG_FATAL in debug mode, ERROR in normal mode
315 #ifdef NDEBUG
316 const LogSeverity LOG_DFATAL = LOG_ERROR;
317 #else
318 const LogSeverity LOG_DFATAL = LOG_FATAL;
319 #endif
321 // A few definitions of macros that don't generate much code. These are used
322 // by LOG() and LOG_IF, etc. Since these are used all over our code, it's
323 // better to have compact code for these operations.
324 #define COMPACT_GOOGLE_LOG_EX_INFO(ClassName, ...) \
325 logging::ClassName(__FILE__, __LINE__, logging::LOG_INFO , ##__VA_ARGS__)
326 #define COMPACT_GOOGLE_LOG_EX_WARNING(ClassName, ...) \
327 logging::ClassName(__FILE__, __LINE__, logging::LOG_WARNING , ##__VA_ARGS__)
328 #define COMPACT_GOOGLE_LOG_EX_ERROR(ClassName, ...) \
329 logging::ClassName(__FILE__, __LINE__, logging::LOG_ERROR , ##__VA_ARGS__)
330 #define COMPACT_GOOGLE_LOG_EX_ERROR_REPORT(ClassName, ...) \
331 logging::ClassName(__FILE__, __LINE__, \
332 logging::LOG_ERROR_REPORT , ##__VA_ARGS__)
333 #define COMPACT_GOOGLE_LOG_EX_FATAL(ClassName, ...) \
334 logging::ClassName(__FILE__, __LINE__, logging::LOG_FATAL , ##__VA_ARGS__)
335 #define COMPACT_GOOGLE_LOG_EX_DFATAL(ClassName, ...) \
336 logging::ClassName(__FILE__, __LINE__, logging::LOG_DFATAL , ##__VA_ARGS__)
338 #define COMPACT_GOOGLE_LOG_INFO \
339 COMPACT_GOOGLE_LOG_EX_INFO(LogMessage)
340 #define COMPACT_GOOGLE_LOG_WARNING \
341 COMPACT_GOOGLE_LOG_EX_WARNING(LogMessage)
342 #define COMPACT_GOOGLE_LOG_ERROR \
343 COMPACT_GOOGLE_LOG_EX_ERROR(LogMessage)
344 #define COMPACT_GOOGLE_LOG_ERROR_REPORT \
345 COMPACT_GOOGLE_LOG_EX_ERROR_REPORT(LogMessage)
346 #define COMPACT_GOOGLE_LOG_FATAL \
347 COMPACT_GOOGLE_LOG_EX_FATAL(LogMessage)
348 #define COMPACT_GOOGLE_LOG_DFATAL \
349 COMPACT_GOOGLE_LOG_EX_DFATAL(LogMessage)
351 #if defined(OS_WIN)
352 // wingdi.h defines ERROR to be 0. When we call LOG(ERROR), it gets
353 // substituted with 0, and it expands to COMPACT_GOOGLE_LOG_0. To allow us
354 // to keep using this syntax, we define this macro to do the same thing
355 // as COMPACT_GOOGLE_LOG_ERROR, and also define ERROR the same way that
356 // the Windows SDK does for consistency.
357 #define ERROR 0
358 #define COMPACT_GOOGLE_LOG_EX_0(ClassName, ...) \
359 COMPACT_GOOGLE_LOG_EX_ERROR(ClassName , ##__VA_ARGS__)
360 #define COMPACT_GOOGLE_LOG_0 COMPACT_GOOGLE_LOG_ERROR
361 // Needed for LOG_IS_ON(ERROR).
362 const LogSeverity LOG_0 = LOG_ERROR;
363 #endif
365 // As special cases, we can assume that LOG_IS_ON(ERROR_REPORT) and
366 // LOG_IS_ON(FATAL) always hold. Also, LOG_IS_ON(DFATAL) always holds
367 // in debug mode. In particular, CHECK()s will always fire if they
368 // fail.
369 #define LOG_IS_ON(severity) \
370 ((::logging::LOG_ ## severity) >= ::logging::GetMinLogLevel())
372 // We can't do any caching tricks with VLOG_IS_ON() like the
373 // google-glog version since it requires GCC extensions. This means
374 // that using the v-logging functions in conjunction with --vmodule
375 // may be slow.
376 #define VLOG_IS_ON(verboselevel) \
377 ((verboselevel) <= ::logging::GetVlogLevel(__FILE__))
379 // Helper macro which avoids evaluating the arguments to a stream if
380 // the condition doesn't hold.
381 #define LAZY_STREAM(stream, condition) \
382 !(condition) ? (void) 0 : ::logging::LogMessageVoidify() & (stream)
384 // We use the preprocessor's merging operator, "##", so that, e.g.,
385 // LOG(INFO) becomes the token COMPACT_GOOGLE_LOG_INFO. There's some funny
386 // subtle difference between ostream member streaming functions (e.g.,
387 // ostream::operator<<(int) and ostream non-member streaming functions
388 // (e.g., ::operator<<(ostream&, string&): it turns out that it's
389 // impossible to stream something like a string directly to an unnamed
390 // ostream. We employ a neat hack by calling the stream() member
391 // function of LogMessage which seems to avoid the problem.
392 #define LOG_STREAM(severity) COMPACT_GOOGLE_LOG_ ## severity.stream()
394 #define LOG(severity) LAZY_STREAM(LOG_STREAM(severity), LOG_IS_ON(severity))
395 #define LOG_IF(severity, condition) \
396 LAZY_STREAM(LOG_STREAM(severity), LOG_IS_ON(severity) && (condition))
398 #define SYSLOG(severity) LOG(severity)
399 #define SYSLOG_IF(severity, condition) LOG_IF(severity, condition)
401 // The VLOG macros log with negative verbosities.
402 #define VLOG_STREAM(verbose_level) \
403 logging::LogMessage(__FILE__, __LINE__, -verbose_level).stream()
405 #define VLOG(verbose_level) \
406 LAZY_STREAM(VLOG_STREAM(verbose_level), VLOG_IS_ON(verbose_level))
408 #define VLOG_IF(verbose_level, condition) \
409 LAZY_STREAM(VLOG_STREAM(verbose_level), \
410 VLOG_IS_ON(verbose_level) && (condition))
412 #if defined (OS_WIN)
413 #define VPLOG_STREAM(verbose_level) \
414 logging::Win32ErrorLogMessage(__FILE__, __LINE__, -verbose_level, \
415 ::logging::GetLastSystemErrorCode()).stream()
416 #elif defined(OS_POSIX)
417 #define VPLOG_STREAM(verbose_level) \
418 logging::ErrnoLogMessage(__FILE__, __LINE__, -verbose_level, \
419 ::logging::GetLastSystemErrorCode()).stream()
420 #endif
422 #define VPLOG(verbose_level) \
423 LAZY_STREAM(VPLOG_STREAM(verbose_level), VLOG_IS_ON(verbose_level))
425 #define VPLOG_IF(verbose_level, condition) \
426 LAZY_STREAM(VPLOG_STREAM(verbose_level), \
427 VLOG_IS_ON(verbose_level) && (condition))
429 // TODO(akalin): Add more VLOG variants, e.g. VPLOG.
431 #define LOG_ASSERT(condition) \
432 LOG_IF(FATAL, !(condition)) << "Assert failed: " #condition ". "
433 #define SYSLOG_ASSERT(condition) \
434 SYSLOG_IF(FATAL, !(condition)) << "Assert failed: " #condition ". "
436 #if defined(OS_WIN)
437 #define LOG_GETLASTERROR_STREAM(severity) \
438 COMPACT_GOOGLE_LOG_EX_ ## severity(Win32ErrorLogMessage, \
439 ::logging::GetLastSystemErrorCode()).stream()
440 #define LOG_GETLASTERROR(severity) \
441 LAZY_STREAM(LOG_GETLASTERROR_STREAM(severity), LOG_IS_ON(severity))
442 #define LOG_GETLASTERROR_MODULE_STREAM(severity, module) \
443 COMPACT_GOOGLE_LOG_EX_ ## severity(Win32ErrorLogMessage, \
444 ::logging::GetLastSystemErrorCode(), module).stream()
445 #define LOG_GETLASTERROR_MODULE(severity, module) \
446 LAZY_STREAM(LOG_GETLASTERROR_STREAM(severity, module), \
447 LOG_IS_ON(severity))
448 // PLOG_STREAM is used by PLOG, which is the usual error logging macro
449 // for each platform.
450 #define PLOG_STREAM(severity) LOG_GETLASTERROR_STREAM(severity)
451 #elif defined(OS_POSIX)
452 #define LOG_ERRNO_STREAM(severity) \
453 COMPACT_GOOGLE_LOG_EX_ ## severity(ErrnoLogMessage, \
454 ::logging::GetLastSystemErrorCode()).stream()
455 #define LOG_ERRNO(severity) \
456 LAZY_STREAM(LOG_ERRNO_STREAM(severity), LOG_IS_ON(severity))
457 // PLOG_STREAM is used by PLOG, which is the usual error logging macro
458 // for each platform.
459 #define PLOG_STREAM(severity) LOG_ERRNO_STREAM(severity)
460 #endif
462 #define PLOG(severity) \
463 LAZY_STREAM(PLOG_STREAM(severity), LOG_IS_ON(severity))
465 #define PLOG_IF(severity, condition) \
466 LAZY_STREAM(PLOG_STREAM(severity), LOG_IS_ON(severity) && (condition))
468 #if !defined(NDEBUG)
469 // Debug builds always include DCHECK and DLOG.
470 #undef LOGGING_IS_OFFICIAL_BUILD
471 #define LOGGING_IS_OFFICIAL_BUILD 0
472 #elif defined(OFFICIAL_BUILD)
473 // Official release builds always disable and remove DCHECK and DLOG.
474 #undef LOGGING_IS_OFFICIAL_BUILD
475 #define LOGGING_IS_OFFICIAL_BUILD 1
476 #elif !defined(LOGGING_IS_OFFICIAL_BUILD)
477 // Unless otherwise specified, unofficial release builds include
478 // DCHECK and DLOG.
479 #define LOGGING_IS_OFFICIAL_BUILD 0
480 #endif
482 // The actual stream used isn't important.
483 #define EAT_STREAM_PARAMETERS \
484 true ? (void) 0 : ::logging::LogMessageVoidify() & LOG_STREAM(FATAL)
486 // CHECK dies with a fatal error if condition is not true. It is *not*
487 // controlled by NDEBUG, so the check will be executed regardless of
488 // compilation mode.
490 // We make sure CHECK et al. always evaluates their arguments, as
491 // doing CHECK(FunctionWithSideEffect()) is a common idiom.
493 #if LOGGING_IS_OFFICIAL_BUILD
495 // Make all CHECK functions discard their log strings to reduce code
496 // bloat for official builds.
498 // TODO(akalin): This would be more valuable if there were some way to
499 // remove BreakDebugger() from the backtrace, perhaps by turning it
500 // into a macro (like __debugbreak() on Windows).
501 #define CHECK(condition) \
502 !(condition) ? ::base::debug::BreakDebugger() : EAT_STREAM_PARAMETERS
504 #define PCHECK(condition) CHECK(condition)
506 #define CHECK_OP(name, op, val1, val2) CHECK((val1) op (val2))
508 #else
510 #define CHECK(condition) \
511 LAZY_STREAM(LOG_STREAM(FATAL), !(condition)) \
512 << "Check failed: " #condition ". "
514 #define PCHECK(condition) \
515 LAZY_STREAM(PLOG_STREAM(FATAL), !(condition)) \
516 << "Check failed: " #condition ". "
518 // Helper macro for binary operators.
519 // Don't use this macro directly in your code, use CHECK_EQ et al below.
521 // TODO(akalin): Rewrite this so that constructs like if (...)
522 // CHECK_EQ(...) else { ... } work properly.
523 #define CHECK_OP(name, op, val1, val2) \
524 if (std::string* _result = \
525 logging::Check##name##Impl((val1), (val2), \
526 #val1 " " #op " " #val2)) \
527 logging::LogMessage(__FILE__, __LINE__, _result).stream()
529 #endif
531 // Build the error message string. This is separate from the "Impl"
532 // function template because it is not performance critical and so can
533 // be out of line, while the "Impl" code should be inline. Caller
534 // takes ownership of the returned string.
535 template<class t1, class t2>
536 std::string* MakeCheckOpString(const t1& v1, const t2& v2, const char* names) {
537 std::ostringstream ss;
538 ss << names << " (" << v1 << " vs. " << v2 << ")";
539 std::string* msg = new std::string(ss.str());
540 return msg;
543 // MSVC doesn't like complex extern templates and DLLs.
544 #if !defined(COMPILER_MSVC)
545 // Commonly used instantiations of MakeCheckOpString<>. Explicitly instantiated
546 // in logging.cc.
547 extern template BASE_EXPORT std::string* MakeCheckOpString<int, int>(
548 const int&, const int&, const char* names);
549 extern template BASE_EXPORT
550 std::string* MakeCheckOpString<unsigned long, unsigned long>(
551 const unsigned long&, const unsigned long&, const char* names);
552 extern template BASE_EXPORT
553 std::string* MakeCheckOpString<unsigned long, unsigned int>(
554 const unsigned long&, const unsigned int&, const char* names);
555 extern template BASE_EXPORT
556 std::string* MakeCheckOpString<unsigned int, unsigned long>(
557 const unsigned int&, const unsigned long&, const char* names);
558 extern template BASE_EXPORT
559 std::string* MakeCheckOpString<std::string, std::string>(
560 const std::string&, const std::string&, const char* name);
561 #endif
563 // Helper functions for CHECK_OP macro.
564 // The (int, int) specialization works around the issue that the compiler
565 // will not instantiate the template version of the function on values of
566 // unnamed enum type - see comment below.
567 #define DEFINE_CHECK_OP_IMPL(name, op) \
568 template <class t1, class t2> \
569 inline std::string* Check##name##Impl(const t1& v1, const t2& v2, \
570 const char* names) { \
571 if (v1 op v2) return NULL; \
572 else return MakeCheckOpString(v1, v2, names); \
574 inline std::string* Check##name##Impl(int v1, int v2, const char* names) { \
575 if (v1 op v2) return NULL; \
576 else return MakeCheckOpString(v1, v2, names); \
578 DEFINE_CHECK_OP_IMPL(EQ, ==)
579 DEFINE_CHECK_OP_IMPL(NE, !=)
580 DEFINE_CHECK_OP_IMPL(LE, <=)
581 DEFINE_CHECK_OP_IMPL(LT, < )
582 DEFINE_CHECK_OP_IMPL(GE, >=)
583 DEFINE_CHECK_OP_IMPL(GT, > )
584 #undef DEFINE_CHECK_OP_IMPL
586 #define CHECK_EQ(val1, val2) CHECK_OP(EQ, ==, val1, val2)
587 #define CHECK_NE(val1, val2) CHECK_OP(NE, !=, val1, val2)
588 #define CHECK_LE(val1, val2) CHECK_OP(LE, <=, val1, val2)
589 #define CHECK_LT(val1, val2) CHECK_OP(LT, < , val1, val2)
590 #define CHECK_GE(val1, val2) CHECK_OP(GE, >=, val1, val2)
591 #define CHECK_GT(val1, val2) CHECK_OP(GT, > , val1, val2)
593 #if LOGGING_IS_OFFICIAL_BUILD
594 // In order to have optimized code for official builds, remove DLOGs and
595 // DCHECKs.
596 #define ENABLE_DLOG 0
597 #define ENABLE_DCHECK 0
599 #elif defined(NDEBUG)
600 // Otherwise, if we're a release build, remove DLOGs but not DCHECKs
601 // (since those can still be turned on via a command-line flag).
602 #define ENABLE_DLOG 0
603 #define ENABLE_DCHECK 1
605 #else
606 // Otherwise, we're a debug build so enable DLOGs and DCHECKs.
607 #define ENABLE_DLOG 1
608 #define ENABLE_DCHECK 1
609 #endif
611 // Definitions for DLOG et al.
613 #if ENABLE_DLOG
615 #define DLOG_IS_ON(severity) LOG_IS_ON(severity)
616 #define DLOG_IF(severity, condition) LOG_IF(severity, condition)
617 #define DLOG_ASSERT(condition) LOG_ASSERT(condition)
618 #define DPLOG_IF(severity, condition) PLOG_IF(severity, condition)
619 #define DVLOG_IF(verboselevel, condition) VLOG_IF(verboselevel, condition)
620 #define DVPLOG_IF(verboselevel, condition) VPLOG_IF(verboselevel, condition)
622 #else // ENABLE_DLOG
624 // If ENABLE_DLOG is off, we want to avoid emitting any references to
625 // |condition| (which may reference a variable defined only if NDEBUG
626 // is not defined). Contrast this with DCHECK et al., which has
627 // different behavior.
629 #define DLOG_IS_ON(severity) false
630 #define DLOG_IF(severity, condition) EAT_STREAM_PARAMETERS
631 #define DLOG_ASSERT(condition) EAT_STREAM_PARAMETERS
632 #define DPLOG_IF(severity, condition) EAT_STREAM_PARAMETERS
633 #define DVLOG_IF(verboselevel, condition) EAT_STREAM_PARAMETERS
634 #define DVPLOG_IF(verboselevel, condition) EAT_STREAM_PARAMETERS
636 #endif // ENABLE_DLOG
638 // DEBUG_MODE is for uses like
639 // if (DEBUG_MODE) foo.CheckThatFoo();
640 // instead of
641 // #ifndef NDEBUG
642 // foo.CheckThatFoo();
643 // #endif
645 // We tie its state to ENABLE_DLOG.
646 enum { DEBUG_MODE = ENABLE_DLOG };
648 #undef ENABLE_DLOG
650 #define DLOG(severity) \
651 LAZY_STREAM(LOG_STREAM(severity), DLOG_IS_ON(severity))
653 #if defined(OS_WIN)
654 #define DLOG_GETLASTERROR(severity) \
655 LAZY_STREAM(LOG_GETLASTERROR_STREAM(severity), DLOG_IS_ON(severity))
656 #define DLOG_GETLASTERROR_MODULE(severity, module) \
657 LAZY_STREAM(LOG_GETLASTERROR_STREAM(severity, module), \
658 DLOG_IS_ON(severity))
659 #elif defined(OS_POSIX)
660 #define DLOG_ERRNO(severity) \
661 LAZY_STREAM(LOG_ERRNO_STREAM(severity), DLOG_IS_ON(severity))
662 #endif
664 #define DPLOG(severity) \
665 LAZY_STREAM(PLOG_STREAM(severity), DLOG_IS_ON(severity))
667 #define DVLOG(verboselevel) DVLOG_IF(verboselevel, VLOG_IS_ON(verboselevel))
669 #define DVPLOG(verboselevel) DVPLOG_IF(verboselevel, VLOG_IS_ON(verboselevel))
671 // Definitions for DCHECK et al.
673 #if ENABLE_DCHECK
675 #if defined(NDEBUG)
677 BASE_EXPORT DcheckState get_dcheck_state();
678 BASE_EXPORT void set_dcheck_state(DcheckState state);
680 #if defined(DCHECK_ALWAYS_ON)
682 #define DCHECK_IS_ON() true
683 #define COMPACT_GOOGLE_LOG_EX_DCHECK(ClassName, ...) \
684 COMPACT_GOOGLE_LOG_EX_FATAL(ClassName , ##__VA_ARGS__)
685 #define COMPACT_GOOGLE_LOG_DCHECK COMPACT_GOOGLE_LOG_FATAL
686 const LogSeverity LOG_DCHECK = LOG_FATAL;
688 #else
690 #define COMPACT_GOOGLE_LOG_EX_DCHECK(ClassName, ...) \
691 COMPACT_GOOGLE_LOG_EX_ERROR_REPORT(ClassName , ##__VA_ARGS__)
692 #define COMPACT_GOOGLE_LOG_DCHECK COMPACT_GOOGLE_LOG_ERROR_REPORT
693 const LogSeverity LOG_DCHECK = LOG_ERROR_REPORT;
694 #define DCHECK_IS_ON() \
695 ((::logging::get_dcheck_state() == \
696 ::logging::ENABLE_DCHECK_FOR_NON_OFFICIAL_RELEASE_BUILDS) && \
697 LOG_IS_ON(DCHECK))
699 #endif // defined(DCHECK_ALWAYS_ON)
701 #else // defined(NDEBUG)
703 // On a regular debug build, we want to have DCHECKs enabled.
704 #define COMPACT_GOOGLE_LOG_EX_DCHECK(ClassName, ...) \
705 COMPACT_GOOGLE_LOG_EX_FATAL(ClassName , ##__VA_ARGS__)
706 #define COMPACT_GOOGLE_LOG_DCHECK COMPACT_GOOGLE_LOG_FATAL
707 const LogSeverity LOG_DCHECK = LOG_FATAL;
708 #define DCHECK_IS_ON() true
710 #endif // defined(NDEBUG)
712 #else // ENABLE_DCHECK
714 // These are just dummy values since DCHECK_IS_ON() is always false in
715 // this case.
716 #define COMPACT_GOOGLE_LOG_EX_DCHECK(ClassName, ...) \
717 COMPACT_GOOGLE_LOG_EX_INFO(ClassName , ##__VA_ARGS__)
718 #define COMPACT_GOOGLE_LOG_DCHECK COMPACT_GOOGLE_LOG_INFO
719 const LogSeverity LOG_DCHECK = LOG_INFO;
720 #define DCHECK_IS_ON() false
722 #endif // ENABLE_DCHECK
723 #undef ENABLE_DCHECK
725 // DCHECK et al. make sure to reference |condition| regardless of
726 // whether DCHECKs are enabled; this is so that we don't get unused
727 // variable warnings if the only use of a variable is in a DCHECK.
728 // This behavior is different from DLOG_IF et al.
730 #define DCHECK(condition) \
731 LAZY_STREAM(LOG_STREAM(DCHECK), DCHECK_IS_ON() && !(condition)) \
732 << "Check failed: " #condition ". "
734 #define DPCHECK(condition) \
735 LAZY_STREAM(PLOG_STREAM(DCHECK), DCHECK_IS_ON() && !(condition)) \
736 << "Check failed: " #condition ". "
738 // Helper macro for binary operators.
739 // Don't use this macro directly in your code, use DCHECK_EQ et al below.
740 #define DCHECK_OP(name, op, val1, val2) \
741 if (DCHECK_IS_ON()) \
742 if (std::string* _result = \
743 logging::Check##name##Impl((val1), (val2), \
744 #val1 " " #op " " #val2)) \
745 logging::LogMessage( \
746 __FILE__, __LINE__, ::logging::LOG_DCHECK, \
747 _result).stream()
749 // Equality/Inequality checks - compare two values, and log a
750 // LOG_DCHECK message including the two values when the result is not
751 // as expected. The values must have operator<<(ostream, ...)
752 // defined.
754 // You may append to the error message like so:
755 // DCHECK_NE(1, 2) << ": The world must be ending!";
757 // We are very careful to ensure that each argument is evaluated exactly
758 // once, and that anything which is legal to pass as a function argument is
759 // legal here. In particular, the arguments may be temporary expressions
760 // which will end up being destroyed at the end of the apparent statement,
761 // for example:
762 // DCHECK_EQ(string("abc")[1], 'b');
764 // WARNING: These may not compile correctly if one of the arguments is a pointer
765 // and the other is NULL. To work around this, simply static_cast NULL to the
766 // type of the desired pointer.
768 #define DCHECK_EQ(val1, val2) DCHECK_OP(EQ, ==, val1, val2)
769 #define DCHECK_NE(val1, val2) DCHECK_OP(NE, !=, val1, val2)
770 #define DCHECK_LE(val1, val2) DCHECK_OP(LE, <=, val1, val2)
771 #define DCHECK_LT(val1, val2) DCHECK_OP(LT, < , val1, val2)
772 #define DCHECK_GE(val1, val2) DCHECK_OP(GE, >=, val1, val2)
773 #define DCHECK_GT(val1, val2) DCHECK_OP(GT, > , val1, val2)
775 #if defined(NDEBUG) && defined(OS_CHROMEOS)
776 #define NOTREACHED() LOG(ERROR) << "NOTREACHED() hit in " << \
777 __FUNCTION__ << ". "
778 #else
779 #define NOTREACHED() DCHECK(false)
780 #endif
782 // Redefine the standard assert to use our nice log files
783 #undef assert
784 #define assert(x) DLOG_ASSERT(x)
786 // This class more or less represents a particular log message. You
787 // create an instance of LogMessage and then stream stuff to it.
788 // When you finish streaming to it, ~LogMessage is called and the
789 // full message gets streamed to the appropriate destination.
791 // You shouldn't actually use LogMessage's constructor to log things,
792 // though. You should use the LOG() macro (and variants thereof)
793 // above.
794 class BASE_EXPORT LogMessage {
795 public:
796 LogMessage(const char* file, int line, LogSeverity severity, int ctr);
798 // Two special constructors that generate reduced amounts of code at
799 // LOG call sites for common cases.
801 // Used for LOG(INFO): Implied are:
802 // severity = LOG_INFO, ctr = 0
804 // Using this constructor instead of the more complex constructor above
805 // saves a couple of bytes per call site.
806 LogMessage(const char* file, int line);
808 // Used for LOG(severity) where severity != INFO. Implied
809 // are: ctr = 0
811 // Using this constructor instead of the more complex constructor above
812 // saves a couple of bytes per call site.
813 LogMessage(const char* file, int line, LogSeverity severity);
815 // A special constructor used for check failures. Takes ownership
816 // of the given string.
817 // Implied severity = LOG_FATAL
818 LogMessage(const char* file, int line, std::string* result);
820 // A special constructor used for check failures, with the option to
821 // specify severity. Takes ownership of the given string.
822 LogMessage(const char* file, int line, LogSeverity severity,
823 std::string* result);
825 ~LogMessage();
827 std::ostream& stream() { return stream_; }
829 private:
830 void Init(const char* file, int line);
832 LogSeverity severity_;
833 std::ostringstream stream_;
834 size_t message_start_; // Offset of the start of the message (past prefix
835 // info).
836 // The file and line information passed in to the constructor.
837 const char* file_;
838 const int line_;
840 #if defined(OS_WIN)
841 // Stores the current value of GetLastError in the constructor and restores
842 // it in the destructor by calling SetLastError.
843 // This is useful since the LogMessage class uses a lot of Win32 calls
844 // that will lose the value of GLE and the code that called the log function
845 // will have lost the thread error value when the log call returns.
846 class SaveLastError {
847 public:
848 SaveLastError();
849 ~SaveLastError();
851 unsigned long get_error() const { return last_error_; }
853 protected:
854 unsigned long last_error_;
857 SaveLastError last_error_;
858 #endif
860 DISALLOW_COPY_AND_ASSIGN(LogMessage);
863 // A non-macro interface to the log facility; (useful
864 // when the logging level is not a compile-time constant).
865 inline void LogAtLevel(int const log_level, std::string const &msg) {
866 LogMessage(__FILE__, __LINE__, log_level).stream() << msg;
869 // This class is used to explicitly ignore values in the conditional
870 // logging macros. This avoids compiler warnings like "value computed
871 // is not used" and "statement has no effect".
872 class LogMessageVoidify {
873 public:
874 LogMessageVoidify() { }
875 // This has to be an operator with a precedence lower than << but
876 // higher than ?:
877 void operator&(std::ostream&) { }
880 #if defined(OS_WIN)
881 typedef unsigned long SystemErrorCode;
882 #elif defined(OS_POSIX)
883 typedef int SystemErrorCode;
884 #endif
886 // Alias for ::GetLastError() on Windows and errno on POSIX. Avoids having to
887 // pull in windows.h just for GetLastError() and DWORD.
888 BASE_EXPORT SystemErrorCode GetLastSystemErrorCode();
890 #if defined(OS_WIN)
891 // Appends a formatted system message of the GetLastError() type.
892 class BASE_EXPORT Win32ErrorLogMessage {
893 public:
894 Win32ErrorLogMessage(const char* file,
895 int line,
896 LogSeverity severity,
897 SystemErrorCode err,
898 const char* module);
900 Win32ErrorLogMessage(const char* file,
901 int line,
902 LogSeverity severity,
903 SystemErrorCode err);
905 // Appends the error message before destructing the encapsulated class.
906 ~Win32ErrorLogMessage();
908 std::ostream& stream() { return log_message_.stream(); }
910 private:
911 SystemErrorCode err_;
912 // Optional name of the module defining the error.
913 const char* module_;
914 LogMessage log_message_;
916 DISALLOW_COPY_AND_ASSIGN(Win32ErrorLogMessage);
918 #elif defined(OS_POSIX)
919 // Appends a formatted system message of the errno type
920 class BASE_EXPORT ErrnoLogMessage {
921 public:
922 ErrnoLogMessage(const char* file,
923 int line,
924 LogSeverity severity,
925 SystemErrorCode err);
927 // Appends the error message before destructing the encapsulated class.
928 ~ErrnoLogMessage();
930 std::ostream& stream() { return log_message_.stream(); }
932 private:
933 SystemErrorCode err_;
934 LogMessage log_message_;
936 DISALLOW_COPY_AND_ASSIGN(ErrnoLogMessage);
938 #endif // OS_WIN
940 // Closes the log file explicitly if open.
941 // NOTE: Since the log file is opened as necessary by the action of logging
942 // statements, there's no guarantee that it will stay closed
943 // after this call.
944 BASE_EXPORT void CloseLogFile();
946 // Async signal safe logging mechanism.
947 BASE_EXPORT void RawLog(int level, const char* message);
949 #define RAW_LOG(level, message) logging::RawLog(logging::LOG_ ## level, message)
951 #define RAW_CHECK(condition) \
952 do { \
953 if (!(condition)) \
954 logging::RawLog(logging::LOG_FATAL, "Check failed: " #condition "\n"); \
955 } while (0)
957 #if defined(OS_WIN)
958 // Returns the default log file path.
959 BASE_EXPORT std::wstring GetLogFileFullPath();
960 #endif
962 } // namespace logging
964 // These functions are provided as a convenience for logging, which is where we
965 // use streams (it is against Google style to use streams in other places). It
966 // is designed to allow you to emit non-ASCII Unicode strings to the log file,
967 // which is normally ASCII. It is relatively slow, so try not to use it for
968 // common cases. Non-ASCII characters will be converted to UTF-8 by these
969 // operators.
970 BASE_EXPORT std::ostream& operator<<(std::ostream& out, const wchar_t* wstr);
971 inline std::ostream& operator<<(std::ostream& out, const std::wstring& wstr) {
972 return out << wstr.c_str();
975 // The NOTIMPLEMENTED() macro annotates codepaths which have
976 // not been implemented yet.
978 // The implementation of this macro is controlled by NOTIMPLEMENTED_POLICY:
979 // 0 -- Do nothing (stripped by compiler)
980 // 1 -- Warn at compile time
981 // 2 -- Fail at compile time
982 // 3 -- Fail at runtime (DCHECK)
983 // 4 -- [default] LOG(ERROR) at runtime
984 // 5 -- LOG(ERROR) at runtime, only once per call-site
986 #ifndef NOTIMPLEMENTED_POLICY
987 #if defined(OS_ANDROID) && defined(OFFICIAL_BUILD)
988 #define NOTIMPLEMENTED_POLICY 0
989 #else
990 // Select default policy: LOG(ERROR)
991 #define NOTIMPLEMENTED_POLICY 4
992 #endif
993 #endif
995 #if defined(COMPILER_GCC)
996 // On Linux, with GCC, we can use __PRETTY_FUNCTION__ to get the demangled name
997 // of the current function in the NOTIMPLEMENTED message.
998 #define NOTIMPLEMENTED_MSG "Not implemented reached in " << __PRETTY_FUNCTION__
999 #else
1000 #define NOTIMPLEMENTED_MSG "NOT IMPLEMENTED"
1001 #endif
1003 #if NOTIMPLEMENTED_POLICY == 0
1004 #define NOTIMPLEMENTED() EAT_STREAM_PARAMETERS
1005 #elif NOTIMPLEMENTED_POLICY == 1
1006 // TODO, figure out how to generate a warning
1007 #define NOTIMPLEMENTED() COMPILE_ASSERT(false, NOT_IMPLEMENTED)
1008 #elif NOTIMPLEMENTED_POLICY == 2
1009 #define NOTIMPLEMENTED() COMPILE_ASSERT(false, NOT_IMPLEMENTED)
1010 #elif NOTIMPLEMENTED_POLICY == 3
1011 #define NOTIMPLEMENTED() NOTREACHED()
1012 #elif NOTIMPLEMENTED_POLICY == 4
1013 #define NOTIMPLEMENTED() LOG(ERROR) << NOTIMPLEMENTED_MSG
1014 #elif NOTIMPLEMENTED_POLICY == 5
1015 #define NOTIMPLEMENTED() do {\
1016 static bool logged_once = false;\
1017 LOG_IF(ERROR, !logged_once) << NOTIMPLEMENTED_MSG;\
1018 logged_once = true;\
1019 } while(0);\
1020 EAT_STREAM_PARAMETERS
1021 #endif
1023 #endif // BASE_LOGGING_H_