Add P2PDatagramSocket and P2PStreamSocket interfaces.
[chromium-blink-merge.git] / base / logging.h
blobadc8fb6c21535d76d78ba9900017b4e122f2e707
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, and FATAL.
132 // Very important: logging a message at the FATAL severity level causes
133 // the program to terminate (after the message is logged).
135 // There is the special severity of DFATAL, which logs FATAL in debug mode,
136 // ERROR in normal mode.
138 namespace logging {
140 // TODO(avi): do we want to do a unification of character types here?
141 #if defined(OS_WIN)
142 typedef wchar_t PathChar;
143 #else
144 typedef char PathChar;
145 #endif
147 // Where to record logging output? A flat file and/or system debug log
148 // via OutputDebugString.
149 enum LoggingDestination {
150 LOG_NONE = 0,
151 LOG_TO_FILE = 1 << 0,
152 LOG_TO_SYSTEM_DEBUG_LOG = 1 << 1,
154 LOG_TO_ALL = LOG_TO_FILE | LOG_TO_SYSTEM_DEBUG_LOG,
156 // On Windows, use a file next to the exe; on POSIX platforms, where
157 // it may not even be possible to locate the executable on disk, use
158 // stderr.
159 #if defined(OS_WIN)
160 LOG_DEFAULT = LOG_TO_FILE,
161 #elif defined(OS_POSIX)
162 LOG_DEFAULT = LOG_TO_SYSTEM_DEBUG_LOG,
163 #endif
166 // Indicates that the log file should be locked when being written to.
167 // Unless there is only one single-threaded process that is logging to
168 // the log file, the file should be locked during writes to make each
169 // log output atomic. Other writers will block.
171 // All processes writing to the log file must have their locking set for it to
172 // work properly. Defaults to LOCK_LOG_FILE.
173 enum LogLockingState { LOCK_LOG_FILE, DONT_LOCK_LOG_FILE };
175 // On startup, should we delete or append to an existing log file (if any)?
176 // Defaults to APPEND_TO_OLD_LOG_FILE.
177 enum OldFileDeletionState { DELETE_OLD_LOG_FILE, APPEND_TO_OLD_LOG_FILE };
179 struct BASE_EXPORT LoggingSettings {
180 // The defaults values are:
182 // logging_dest: LOG_DEFAULT
183 // log_file: NULL
184 // lock_log: LOCK_LOG_FILE
185 // delete_old: APPEND_TO_OLD_LOG_FILE
186 LoggingSettings();
188 LoggingDestination logging_dest;
190 // The three settings below have an effect only when LOG_TO_FILE is
191 // set in |logging_dest|.
192 const PathChar* log_file;
193 LogLockingState lock_log;
194 OldFileDeletionState delete_old;
197 // Define different names for the BaseInitLoggingImpl() function depending on
198 // whether NDEBUG is defined or not so that we'll fail to link if someone tries
199 // to compile logging.cc with NDEBUG but includes logging.h without defining it,
200 // or vice versa.
201 #if NDEBUG
202 #define BaseInitLoggingImpl BaseInitLoggingImpl_built_with_NDEBUG
203 #else
204 #define BaseInitLoggingImpl BaseInitLoggingImpl_built_without_NDEBUG
205 #endif
207 // Implementation of the InitLogging() method declared below. We use a
208 // more-specific name so we can #define it above without affecting other code
209 // that has named stuff "InitLogging".
210 BASE_EXPORT bool BaseInitLoggingImpl(const LoggingSettings& settings);
212 // Sets the log file name and other global logging state. Calling this function
213 // is recommended, and is normally done at the beginning of application init.
214 // If you don't call it, all the flags will be initialized to their default
215 // values, and there is a race condition that may leak a critical section
216 // object if two threads try to do the first log at the same time.
217 // See the definition of the enums above for descriptions and default values.
219 // The default log file is initialized to "debug.log" in the application
220 // directory. You probably don't want this, especially since the program
221 // directory may not be writable on an enduser's system.
223 // This function may be called a second time to re-direct logging (e.g after
224 // loging in to a user partition), however it should never be called more than
225 // twice.
226 inline bool InitLogging(const LoggingSettings& settings) {
227 return BaseInitLoggingImpl(settings);
230 // Sets the log level. Anything at or above this level will be written to the
231 // log file/displayed to the user (if applicable). Anything below this level
232 // will be silently ignored. The log level defaults to 0 (everything is logged
233 // up to level INFO) if this function is not called.
234 // Note that log messages for VLOG(x) are logged at level -x, so setting
235 // the min log level to negative values enables verbose logging.
236 BASE_EXPORT void SetMinLogLevel(int level);
238 // Gets the current log level.
239 BASE_EXPORT int GetMinLogLevel();
241 // Gets the VLOG default verbosity level.
242 BASE_EXPORT int GetVlogVerbosity();
244 // Gets the current vlog level for the given file (usually taken from
245 // __FILE__).
247 // Note that |N| is the size *with* the null terminator.
248 BASE_EXPORT int GetVlogLevelHelper(const char* file_start, size_t N);
250 template <size_t N>
251 int GetVlogLevel(const char (&file)[N]) {
252 return GetVlogLevelHelper(file, N);
255 // Sets the common items you want to be prepended to each log message.
256 // process and thread IDs default to off, the timestamp defaults to on.
257 // If this function is not called, logging defaults to writing the timestamp
258 // only.
259 BASE_EXPORT void SetLogItems(bool enable_process_id, bool enable_thread_id,
260 bool enable_timestamp, bool enable_tickcount);
262 // Sets whether or not you'd like to see fatal debug messages popped up in
263 // a dialog box or not.
264 // Dialogs are not shown by default.
265 BASE_EXPORT void SetShowErrorDialogs(bool enable_dialogs);
267 // Sets the Log Assert Handler that will be used to notify of check failures.
268 // The default handler shows a dialog box and then terminate the process,
269 // however clients can use this function to override with their own handling
270 // (e.g. a silent one for Unit Tests)
271 typedef void (*LogAssertHandlerFunction)(const std::string& str);
272 BASE_EXPORT void SetLogAssertHandler(LogAssertHandlerFunction handler);
274 // Sets the Log Message Handler that gets passed every log message before
275 // it's sent to other log destinations (if any).
276 // Returns true to signal that it handled the message and the message
277 // should not be sent to other log destinations.
278 typedef bool (*LogMessageHandlerFunction)(int severity,
279 const char* file, int line, size_t message_start, const std::string& str);
280 BASE_EXPORT void SetLogMessageHandler(LogMessageHandlerFunction handler);
281 BASE_EXPORT LogMessageHandlerFunction GetLogMessageHandler();
283 typedef int LogSeverity;
284 const LogSeverity LOG_VERBOSE = -1; // This is level 1 verbosity
285 // Note: the log severities are used to index into the array of names,
286 // see log_severity_names.
287 const LogSeverity LOG_INFO = 0;
288 const LogSeverity LOG_WARNING = 1;
289 const LogSeverity LOG_ERROR = 2;
290 const LogSeverity LOG_FATAL = 3;
291 const LogSeverity LOG_NUM_SEVERITIES = 4;
293 // LOG_DFATAL is LOG_FATAL in debug mode, ERROR in normal mode
294 #ifdef NDEBUG
295 const LogSeverity LOG_DFATAL = LOG_ERROR;
296 #else
297 const LogSeverity LOG_DFATAL = LOG_FATAL;
298 #endif
300 // A few definitions of macros that don't generate much code. These are used
301 // by LOG() and LOG_IF, etc. Since these are used all over our code, it's
302 // better to have compact code for these operations.
303 #define COMPACT_GOOGLE_LOG_EX_INFO(ClassName, ...) \
304 logging::ClassName(__FILE__, __LINE__, logging::LOG_INFO , ##__VA_ARGS__)
305 #define COMPACT_GOOGLE_LOG_EX_WARNING(ClassName, ...) \
306 logging::ClassName(__FILE__, __LINE__, logging::LOG_WARNING , ##__VA_ARGS__)
307 #define COMPACT_GOOGLE_LOG_EX_ERROR(ClassName, ...) \
308 logging::ClassName(__FILE__, __LINE__, logging::LOG_ERROR , ##__VA_ARGS__)
309 #define COMPACT_GOOGLE_LOG_EX_FATAL(ClassName, ...) \
310 logging::ClassName(__FILE__, __LINE__, logging::LOG_FATAL , ##__VA_ARGS__)
311 #define COMPACT_GOOGLE_LOG_EX_DFATAL(ClassName, ...) \
312 logging::ClassName(__FILE__, __LINE__, logging::LOG_DFATAL , ##__VA_ARGS__)
314 #define COMPACT_GOOGLE_LOG_INFO \
315 COMPACT_GOOGLE_LOG_EX_INFO(LogMessage)
316 #define COMPACT_GOOGLE_LOG_WARNING \
317 COMPACT_GOOGLE_LOG_EX_WARNING(LogMessage)
318 #define COMPACT_GOOGLE_LOG_ERROR \
319 COMPACT_GOOGLE_LOG_EX_ERROR(LogMessage)
320 #define COMPACT_GOOGLE_LOG_FATAL \
321 COMPACT_GOOGLE_LOG_EX_FATAL(LogMessage)
322 #define COMPACT_GOOGLE_LOG_DFATAL \
323 COMPACT_GOOGLE_LOG_EX_DFATAL(LogMessage)
325 #if defined(OS_WIN)
326 // wingdi.h defines ERROR to be 0. When we call LOG(ERROR), it gets
327 // substituted with 0, and it expands to COMPACT_GOOGLE_LOG_0. To allow us
328 // to keep using this syntax, we define this macro to do the same thing
329 // as COMPACT_GOOGLE_LOG_ERROR, and also define ERROR the same way that
330 // the Windows SDK does for consistency.
331 #define ERROR 0
332 #define COMPACT_GOOGLE_LOG_EX_0(ClassName, ...) \
333 COMPACT_GOOGLE_LOG_EX_ERROR(ClassName , ##__VA_ARGS__)
334 #define COMPACT_GOOGLE_LOG_0 COMPACT_GOOGLE_LOG_ERROR
335 // Needed for LOG_IS_ON(ERROR).
336 const LogSeverity LOG_0 = LOG_ERROR;
337 #endif
339 // As special cases, we can assume that LOG_IS_ON(FATAL) always holds. Also,
340 // LOG_IS_ON(DFATAL) always holds in debug mode. In particular, CHECK()s will
341 // always fire if they fail.
342 #define LOG_IS_ON(severity) \
343 ((::logging::LOG_ ## severity) >= ::logging::GetMinLogLevel())
345 // We can't do any caching tricks with VLOG_IS_ON() like the
346 // google-glog version since it requires GCC extensions. This means
347 // that using the v-logging functions in conjunction with --vmodule
348 // may be slow.
349 #define VLOG_IS_ON(verboselevel) \
350 ((verboselevel) <= ::logging::GetVlogLevel(__FILE__))
352 // Helper macro which avoids evaluating the arguments to a stream if
353 // the condition doesn't hold. Condition is evaluated once and only once.
354 #define LAZY_STREAM(stream, condition) \
355 !(condition) ? (void) 0 : ::logging::LogMessageVoidify() & (stream)
357 // We use the preprocessor's merging operator, "##", so that, e.g.,
358 // LOG(INFO) becomes the token COMPACT_GOOGLE_LOG_INFO. There's some funny
359 // subtle difference between ostream member streaming functions (e.g.,
360 // ostream::operator<<(int) and ostream non-member streaming functions
361 // (e.g., ::operator<<(ostream&, string&): it turns out that it's
362 // impossible to stream something like a string directly to an unnamed
363 // ostream. We employ a neat hack by calling the stream() member
364 // function of LogMessage which seems to avoid the problem.
365 #define LOG_STREAM(severity) COMPACT_GOOGLE_LOG_ ## severity.stream()
367 #define LOG(severity) LAZY_STREAM(LOG_STREAM(severity), LOG_IS_ON(severity))
368 #define LOG_IF(severity, condition) \
369 LAZY_STREAM(LOG_STREAM(severity), LOG_IS_ON(severity) && (condition))
371 #define SYSLOG(severity) LOG(severity)
372 #define SYSLOG_IF(severity, condition) LOG_IF(severity, condition)
374 // The VLOG macros log with negative verbosities.
375 #define VLOG_STREAM(verbose_level) \
376 logging::LogMessage(__FILE__, __LINE__, -verbose_level).stream()
378 #define VLOG(verbose_level) \
379 LAZY_STREAM(VLOG_STREAM(verbose_level), VLOG_IS_ON(verbose_level))
381 #define VLOG_IF(verbose_level, condition) \
382 LAZY_STREAM(VLOG_STREAM(verbose_level), \
383 VLOG_IS_ON(verbose_level) && (condition))
385 #if defined (OS_WIN)
386 #define VPLOG_STREAM(verbose_level) \
387 logging::Win32ErrorLogMessage(__FILE__, __LINE__, -verbose_level, \
388 ::logging::GetLastSystemErrorCode()).stream()
389 #elif defined(OS_POSIX)
390 #define VPLOG_STREAM(verbose_level) \
391 logging::ErrnoLogMessage(__FILE__, __LINE__, -verbose_level, \
392 ::logging::GetLastSystemErrorCode()).stream()
393 #endif
395 #define VPLOG(verbose_level) \
396 LAZY_STREAM(VPLOG_STREAM(verbose_level), VLOG_IS_ON(verbose_level))
398 #define VPLOG_IF(verbose_level, condition) \
399 LAZY_STREAM(VPLOG_STREAM(verbose_level), \
400 VLOG_IS_ON(verbose_level) && (condition))
402 // TODO(akalin): Add more VLOG variants, e.g. VPLOG.
404 #define LOG_ASSERT(condition) \
405 LOG_IF(FATAL, !(condition)) << "Assert failed: " #condition ". "
406 #define SYSLOG_ASSERT(condition) \
407 SYSLOG_IF(FATAL, !(condition)) << "Assert failed: " #condition ". "
409 #if defined(OS_WIN)
410 #define PLOG_STREAM(severity) \
411 COMPACT_GOOGLE_LOG_EX_ ## severity(Win32ErrorLogMessage, \
412 ::logging::GetLastSystemErrorCode()).stream()
413 #elif defined(OS_POSIX)
414 #define PLOG_STREAM(severity) \
415 COMPACT_GOOGLE_LOG_EX_ ## severity(ErrnoLogMessage, \
416 ::logging::GetLastSystemErrorCode()).stream()
417 #endif
419 #define PLOG(severity) \
420 LAZY_STREAM(PLOG_STREAM(severity), LOG_IS_ON(severity))
422 #define PLOG_IF(severity, condition) \
423 LAZY_STREAM(PLOG_STREAM(severity), LOG_IS_ON(severity) && (condition))
425 // The actual stream used isn't important.
426 #define EAT_STREAM_PARAMETERS \
427 true ? (void) 0 : ::logging::LogMessageVoidify() & LOG_STREAM(FATAL)
429 // CHECK dies with a fatal error if condition is not true. It is *not*
430 // controlled by NDEBUG, so the check will be executed regardless of
431 // compilation mode.
433 // We make sure CHECK et al. always evaluates their arguments, as
434 // doing CHECK(FunctionWithSideEffect()) is a common idiom.
436 #if defined(OFFICIAL_BUILD) && defined(NDEBUG) && !defined(OS_ANDROID)
438 // Make all CHECK functions discard their log strings to reduce code
439 // bloat for official release builds (except Android).
441 // TODO(akalin): This would be more valuable if there were some way to
442 // remove BreakDebugger() from the backtrace, perhaps by turning it
443 // into a macro (like __debugbreak() on Windows).
444 #define CHECK(condition) \
445 !(condition) ? ::base::debug::BreakDebugger() : EAT_STREAM_PARAMETERS
447 #define PCHECK(condition) CHECK(condition)
449 #define CHECK_OP(name, op, val1, val2) CHECK((val1) op (val2))
451 #else
453 #if defined(_PREFAST_) && defined(OS_WIN)
454 // Use __analysis_assume to tell the VC++ static analysis engine that
455 // assert conditions are true, to suppress warnings. The LAZY_STREAM
456 // parameter doesn't reference 'condition' in /analyze builds because
457 // this evaluation confuses /analyze. The !! before condition is because
458 // __analysis_assume gets confused on some conditions:
459 // http://randomascii.wordpress.com/2011/09/13/analyze-for-visual-studio-the-ugly-part-5/
461 #define CHECK(condition) \
462 __analysis_assume(!!(condition)), \
463 LAZY_STREAM(LOG_STREAM(FATAL), false) \
464 << "Check failed: " #condition ". "
466 #define PCHECK(condition) \
467 __analysis_assume(!!(condition)), \
468 LAZY_STREAM(PLOG_STREAM(FATAL), false) \
469 << "Check failed: " #condition ". "
471 #else // _PREFAST_
473 // Do as much work as possible out of line to reduce inline code size.
474 #define CHECK(condition) \
475 LAZY_STREAM(logging::LogMessage(__FILE__, __LINE__, #condition).stream(), \
476 !(condition))
478 #define PCHECK(condition) \
479 LAZY_STREAM(PLOG_STREAM(FATAL), !(condition)) \
480 << "Check failed: " #condition ". "
482 #endif // _PREFAST_
484 // Helper macro for binary operators.
485 // Don't use this macro directly in your code, use CHECK_EQ et al below.
487 // TODO(akalin): Rewrite this so that constructs like if (...)
488 // CHECK_EQ(...) else { ... } work properly.
489 #define CHECK_OP(name, op, val1, val2) \
490 if (std::string* _result = \
491 logging::Check##name##Impl((val1), (val2), \
492 #val1 " " #op " " #val2)) \
493 logging::LogMessage(__FILE__, __LINE__, _result).stream()
495 #endif
497 // Build the error message string. This is separate from the "Impl"
498 // function template because it is not performance critical and so can
499 // be out of line, while the "Impl" code should be inline. Caller
500 // takes ownership of the returned string.
501 template<class t1, class t2>
502 std::string* MakeCheckOpString(const t1& v1, const t2& v2, const char* names) {
503 std::ostringstream ss;
504 ss << names << " (" << v1 << " vs. " << v2 << ")";
505 std::string* msg = new std::string(ss.str());
506 return msg;
509 // Commonly used instantiations of MakeCheckOpString<>. Explicitly instantiated
510 // in logging.cc.
511 extern template BASE_EXPORT std::string* MakeCheckOpString<int, int>(
512 const int&, const int&, const char* names);
513 extern template BASE_EXPORT
514 std::string* MakeCheckOpString<unsigned long, unsigned long>(
515 const unsigned long&, const unsigned long&, const char* names);
516 extern template BASE_EXPORT
517 std::string* MakeCheckOpString<unsigned long, unsigned int>(
518 const unsigned long&, const unsigned int&, const char* names);
519 extern template BASE_EXPORT
520 std::string* MakeCheckOpString<unsigned int, unsigned long>(
521 const unsigned int&, const unsigned long&, const char* names);
522 extern template BASE_EXPORT
523 std::string* MakeCheckOpString<std::string, std::string>(
524 const std::string&, const std::string&, const char* name);
526 // Helper functions for CHECK_OP macro.
527 // The (int, int) specialization works around the issue that the compiler
528 // will not instantiate the template version of the function on values of
529 // unnamed enum type - see comment below.
530 #define DEFINE_CHECK_OP_IMPL(name, op) \
531 template <class t1, class t2> \
532 inline std::string* Check##name##Impl(const t1& v1, const t2& v2, \
533 const char* names) { \
534 if (v1 op v2) return NULL; \
535 else return MakeCheckOpString(v1, v2, names); \
537 inline std::string* Check##name##Impl(int v1, int v2, const char* names) { \
538 if (v1 op v2) return NULL; \
539 else return MakeCheckOpString(v1, v2, names); \
541 DEFINE_CHECK_OP_IMPL(EQ, ==)
542 DEFINE_CHECK_OP_IMPL(NE, !=)
543 DEFINE_CHECK_OP_IMPL(LE, <=)
544 DEFINE_CHECK_OP_IMPL(LT, < )
545 DEFINE_CHECK_OP_IMPL(GE, >=)
546 DEFINE_CHECK_OP_IMPL(GT, > )
547 #undef DEFINE_CHECK_OP_IMPL
549 #define CHECK_EQ(val1, val2) CHECK_OP(EQ, ==, val1, val2)
550 #define CHECK_NE(val1, val2) CHECK_OP(NE, !=, val1, val2)
551 #define CHECK_LE(val1, val2) CHECK_OP(LE, <=, val1, val2)
552 #define CHECK_LT(val1, val2) CHECK_OP(LT, < , val1, val2)
553 #define CHECK_GE(val1, val2) CHECK_OP(GE, >=, val1, val2)
554 #define CHECK_GT(val1, val2) CHECK_OP(GT, > , val1, val2)
555 #define CHECK_IMPLIES(val1, val2) CHECK(!(val1) || (val2))
557 #if defined(NDEBUG)
558 #define ENABLE_DLOG 0
559 #else
560 #define ENABLE_DLOG 1
561 #endif
563 #if defined(NDEBUG) && !defined(DCHECK_ALWAYS_ON)
564 #define DCHECK_IS_ON() 0
565 #else
566 #define DCHECK_IS_ON() 1
567 #endif
569 // Definitions for DLOG et al.
571 #if ENABLE_DLOG
573 #define DLOG_IS_ON(severity) LOG_IS_ON(severity)
574 #define DLOG_IF(severity, condition) LOG_IF(severity, condition)
575 #define DLOG_ASSERT(condition) LOG_ASSERT(condition)
576 #define DPLOG_IF(severity, condition) PLOG_IF(severity, condition)
577 #define DVLOG_IF(verboselevel, condition) VLOG_IF(verboselevel, condition)
578 #define DVPLOG_IF(verboselevel, condition) VPLOG_IF(verboselevel, condition)
580 #else // ENABLE_DLOG
582 // If ENABLE_DLOG is off, we want to avoid emitting any references to
583 // |condition| (which may reference a variable defined only if NDEBUG
584 // is not defined). Contrast this with DCHECK et al., which has
585 // different behavior.
587 #define DLOG_IS_ON(severity) false
588 #define DLOG_IF(severity, condition) EAT_STREAM_PARAMETERS
589 #define DLOG_ASSERT(condition) EAT_STREAM_PARAMETERS
590 #define DPLOG_IF(severity, condition) EAT_STREAM_PARAMETERS
591 #define DVLOG_IF(verboselevel, condition) EAT_STREAM_PARAMETERS
592 #define DVPLOG_IF(verboselevel, condition) EAT_STREAM_PARAMETERS
594 #endif // ENABLE_DLOG
596 // DEBUG_MODE is for uses like
597 // if (DEBUG_MODE) foo.CheckThatFoo();
598 // instead of
599 // #ifndef NDEBUG
600 // foo.CheckThatFoo();
601 // #endif
603 // We tie its state to ENABLE_DLOG.
604 enum { DEBUG_MODE = ENABLE_DLOG };
606 #undef ENABLE_DLOG
608 #define DLOG(severity) \
609 LAZY_STREAM(LOG_STREAM(severity), DLOG_IS_ON(severity))
611 #define DPLOG(severity) \
612 LAZY_STREAM(PLOG_STREAM(severity), DLOG_IS_ON(severity))
614 #define DVLOG(verboselevel) DVLOG_IF(verboselevel, VLOG_IS_ON(verboselevel))
616 #define DVPLOG(verboselevel) DVPLOG_IF(verboselevel, VLOG_IS_ON(verboselevel))
618 // Definitions for DCHECK et al.
620 #if DCHECK_IS_ON()
622 #define COMPACT_GOOGLE_LOG_EX_DCHECK(ClassName, ...) \
623 COMPACT_GOOGLE_LOG_EX_FATAL(ClassName , ##__VA_ARGS__)
624 #define COMPACT_GOOGLE_LOG_DCHECK COMPACT_GOOGLE_LOG_FATAL
625 const LogSeverity LOG_DCHECK = LOG_FATAL;
627 #else // DCHECK_IS_ON()
629 // These are just dummy values.
630 #define COMPACT_GOOGLE_LOG_EX_DCHECK(ClassName, ...) \
631 COMPACT_GOOGLE_LOG_EX_INFO(ClassName , ##__VA_ARGS__)
632 #define COMPACT_GOOGLE_LOG_DCHECK COMPACT_GOOGLE_LOG_INFO
633 const LogSeverity LOG_DCHECK = LOG_INFO;
635 #endif // DCHECK_IS_ON()
637 // DCHECK et al. make sure to reference |condition| regardless of
638 // whether DCHECKs are enabled; this is so that we don't get unused
639 // variable warnings if the only use of a variable is in a DCHECK.
640 // This behavior is different from DLOG_IF et al.
642 #if defined(_PREFAST_) && defined(OS_WIN)
643 // See comments on the previous use of __analysis_assume.
645 #define DCHECK(condition) \
646 __analysis_assume(!!(condition)), \
647 LAZY_STREAM(LOG_STREAM(DCHECK), false) \
648 << "Check failed: " #condition ". "
650 #define DPCHECK(condition) \
651 __analysis_assume(!!(condition)), \
652 LAZY_STREAM(PLOG_STREAM(DCHECK), false) \
653 << "Check failed: " #condition ". "
655 #else // _PREFAST_
657 #define DCHECK(condition) \
658 LAZY_STREAM(LOG_STREAM(DCHECK), DCHECK_IS_ON() ? !(condition) : false) \
659 << "Check failed: " #condition ". "
661 #define DPCHECK(condition) \
662 LAZY_STREAM(PLOG_STREAM(DCHECK), DCHECK_IS_ON() ? !(condition) : false) \
663 << "Check failed: " #condition ". "
665 #endif // _PREFAST_
667 // Helper macro for binary operators.
668 // Don't use this macro directly in your code, use DCHECK_EQ et al below.
669 #define DCHECK_OP(name, op, val1, val2) \
670 if (DCHECK_IS_ON()) \
671 if (std::string* _result = logging::Check##name##Impl( \
672 (val1), (val2), #val1 " " #op " " #val2)) \
673 logging::LogMessage(__FILE__, __LINE__, ::logging::LOG_DCHECK, _result) \
674 .stream()
676 // Equality/Inequality checks - compare two values, and log a
677 // LOG_DCHECK message including the two values when the result is not
678 // as expected. The values must have operator<<(ostream, ...)
679 // defined.
681 // You may append to the error message like so:
682 // DCHECK_NE(1, 2) << ": The world must be ending!";
684 // We are very careful to ensure that each argument is evaluated exactly
685 // once, and that anything which is legal to pass as a function argument is
686 // legal here. In particular, the arguments may be temporary expressions
687 // which will end up being destroyed at the end of the apparent statement,
688 // for example:
689 // DCHECK_EQ(string("abc")[1], 'b');
691 // WARNING: These may not compile correctly if one of the arguments is a pointer
692 // and the other is NULL. To work around this, simply static_cast NULL to the
693 // type of the desired pointer.
695 #define DCHECK_EQ(val1, val2) DCHECK_OP(EQ, ==, val1, val2)
696 #define DCHECK_NE(val1, val2) DCHECK_OP(NE, !=, val1, val2)
697 #define DCHECK_LE(val1, val2) DCHECK_OP(LE, <=, val1, val2)
698 #define DCHECK_LT(val1, val2) DCHECK_OP(LT, < , val1, val2)
699 #define DCHECK_GE(val1, val2) DCHECK_OP(GE, >=, val1, val2)
700 #define DCHECK_GT(val1, val2) DCHECK_OP(GT, > , val1, val2)
701 #define DCHECK_IMPLIES(val1, val2) DCHECK(!(val1) || (val2))
703 #if !DCHECK_IS_ON() && defined(OS_CHROMEOS)
704 // Implement logging of NOTREACHED() as a dedicated function to get function
705 // call overhead down to a minimum.
706 void LogErrorNotReached(const char* file, int line);
707 #define NOTREACHED() \
708 true ? ::logging::LogErrorNotReached(__FILE__, __LINE__) \
709 : EAT_STREAM_PARAMETERS
710 #else
711 #define NOTREACHED() DCHECK(false)
712 #endif
714 // Redefine the standard assert to use our nice log files
715 #undef assert
716 #define assert(x) DLOG_ASSERT(x)
718 // This class more or less represents a particular log message. You
719 // create an instance of LogMessage and then stream stuff to it.
720 // When you finish streaming to it, ~LogMessage is called and the
721 // full message gets streamed to the appropriate destination.
723 // You shouldn't actually use LogMessage's constructor to log things,
724 // though. You should use the LOG() macro (and variants thereof)
725 // above.
726 class BASE_EXPORT LogMessage {
727 public:
728 // Used for LOG(severity).
729 LogMessage(const char* file, int line, LogSeverity severity);
731 // Used for CHECK(). Implied severity = LOG_FATAL.
732 LogMessage(const char* file, int line, const char* condition);
734 // Used for CHECK_EQ(), etc. Takes ownership of the given string.
735 // Implied severity = LOG_FATAL.
736 LogMessage(const char* file, int line, std::string* result);
738 // Used for DCHECK_EQ(), etc. Takes ownership of the given string.
739 LogMessage(const char* file, int line, LogSeverity severity,
740 std::string* result);
742 ~LogMessage();
744 std::ostream& stream() { return stream_; }
746 private:
747 void Init(const char* file, int line);
749 LogSeverity severity_;
750 std::ostringstream stream_;
751 size_t message_start_; // Offset of the start of the message (past prefix
752 // info).
753 // The file and line information passed in to the constructor.
754 const char* file_;
755 const int line_;
757 #if defined(OS_WIN)
758 // Stores the current value of GetLastError in the constructor and restores
759 // it in the destructor by calling SetLastError.
760 // This is useful since the LogMessage class uses a lot of Win32 calls
761 // that will lose the value of GLE and the code that called the log function
762 // will have lost the thread error value when the log call returns.
763 class SaveLastError {
764 public:
765 SaveLastError();
766 ~SaveLastError();
768 unsigned long get_error() const { return last_error_; }
770 protected:
771 unsigned long last_error_;
774 SaveLastError last_error_;
775 #endif
777 DISALLOW_COPY_AND_ASSIGN(LogMessage);
780 // A non-macro interface to the log facility; (useful
781 // when the logging level is not a compile-time constant).
782 inline void LogAtLevel(int const log_level, std::string const &msg) {
783 LogMessage(__FILE__, __LINE__, log_level).stream() << msg;
786 // This class is used to explicitly ignore values in the conditional
787 // logging macros. This avoids compiler warnings like "value computed
788 // is not used" and "statement has no effect".
789 class LogMessageVoidify {
790 public:
791 LogMessageVoidify() { }
792 // This has to be an operator with a precedence lower than << but
793 // higher than ?:
794 void operator&(std::ostream&) { }
797 #if defined(OS_WIN)
798 typedef unsigned long SystemErrorCode;
799 #elif defined(OS_POSIX)
800 typedef int SystemErrorCode;
801 #endif
803 // Alias for ::GetLastError() on Windows and errno on POSIX. Avoids having to
804 // pull in windows.h just for GetLastError() and DWORD.
805 BASE_EXPORT SystemErrorCode GetLastSystemErrorCode();
806 BASE_EXPORT std::string SystemErrorCodeToString(SystemErrorCode error_code);
808 #if defined(OS_WIN)
809 // Appends a formatted system message of the GetLastError() type.
810 class BASE_EXPORT Win32ErrorLogMessage {
811 public:
812 Win32ErrorLogMessage(const char* file,
813 int line,
814 LogSeverity severity,
815 SystemErrorCode err);
817 // Appends the error message before destructing the encapsulated class.
818 ~Win32ErrorLogMessage();
820 std::ostream& stream() { return log_message_.stream(); }
822 private:
823 SystemErrorCode err_;
824 LogMessage log_message_;
826 DISALLOW_COPY_AND_ASSIGN(Win32ErrorLogMessage);
828 #elif defined(OS_POSIX)
829 // Appends a formatted system message of the errno type
830 class BASE_EXPORT ErrnoLogMessage {
831 public:
832 ErrnoLogMessage(const char* file,
833 int line,
834 LogSeverity severity,
835 SystemErrorCode err);
837 // Appends the error message before destructing the encapsulated class.
838 ~ErrnoLogMessage();
840 std::ostream& stream() { return log_message_.stream(); }
842 private:
843 SystemErrorCode err_;
844 LogMessage log_message_;
846 DISALLOW_COPY_AND_ASSIGN(ErrnoLogMessage);
848 #endif // OS_WIN
850 // Closes the log file explicitly if open.
851 // NOTE: Since the log file is opened as necessary by the action of logging
852 // statements, there's no guarantee that it will stay closed
853 // after this call.
854 BASE_EXPORT void CloseLogFile();
856 // Async signal safe logging mechanism.
857 BASE_EXPORT void RawLog(int level, const char* message);
859 #define RAW_LOG(level, message) logging::RawLog(logging::LOG_ ## level, message)
861 #define RAW_CHECK(condition) \
862 do { \
863 if (!(condition)) \
864 logging::RawLog(logging::LOG_FATAL, "Check failed: " #condition "\n"); \
865 } while (0)
867 #if defined(OS_WIN)
868 // Returns the default log file path.
869 BASE_EXPORT std::wstring GetLogFileFullPath();
870 #endif
872 } // namespace logging
874 // Note that "The behavior of a C++ program is undefined if it adds declarations
875 // or definitions to namespace std or to a namespace within namespace std unless
876 // otherwise specified." --C++11[namespace.std]
878 // We've checked that this particular definition has the intended behavior on
879 // our implementations, but it's prone to breaking in the future, and please
880 // don't imitate this in your own definitions without checking with some
881 // standard library experts.
882 namespace std {
883 // These functions are provided as a convenience for logging, which is where we
884 // use streams (it is against Google style to use streams in other places). It
885 // is designed to allow you to emit non-ASCII Unicode strings to the log file,
886 // which is normally ASCII. It is relatively slow, so try not to use it for
887 // common cases. Non-ASCII characters will be converted to UTF-8 by these
888 // operators.
889 BASE_EXPORT std::ostream& operator<<(std::ostream& out, const wchar_t* wstr);
890 inline std::ostream& operator<<(std::ostream& out, const std::wstring& wstr) {
891 return out << wstr.c_str();
893 } // namespace std
895 // The NOTIMPLEMENTED() macro annotates codepaths which have
896 // not been implemented yet.
898 // The implementation of this macro is controlled by NOTIMPLEMENTED_POLICY:
899 // 0 -- Do nothing (stripped by compiler)
900 // 1 -- Warn at compile time
901 // 2 -- Fail at compile time
902 // 3 -- Fail at runtime (DCHECK)
903 // 4 -- [default] LOG(ERROR) at runtime
904 // 5 -- LOG(ERROR) at runtime, only once per call-site
906 #ifndef NOTIMPLEMENTED_POLICY
907 #if defined(OS_ANDROID) && defined(OFFICIAL_BUILD)
908 #define NOTIMPLEMENTED_POLICY 0
909 #else
910 // Select default policy: LOG(ERROR)
911 #define NOTIMPLEMENTED_POLICY 4
912 #endif
913 #endif
915 #if defined(COMPILER_GCC)
916 // On Linux, with GCC, we can use __PRETTY_FUNCTION__ to get the demangled name
917 // of the current function in the NOTIMPLEMENTED message.
918 #define NOTIMPLEMENTED_MSG "Not implemented reached in " << __PRETTY_FUNCTION__
919 #else
920 #define NOTIMPLEMENTED_MSG "NOT IMPLEMENTED"
921 #endif
923 #if NOTIMPLEMENTED_POLICY == 0
924 #define NOTIMPLEMENTED() EAT_STREAM_PARAMETERS
925 #elif NOTIMPLEMENTED_POLICY == 1
926 // TODO, figure out how to generate a warning
927 #define NOTIMPLEMENTED() COMPILE_ASSERT(false, NOT_IMPLEMENTED)
928 #elif NOTIMPLEMENTED_POLICY == 2
929 #define NOTIMPLEMENTED() COMPILE_ASSERT(false, NOT_IMPLEMENTED)
930 #elif NOTIMPLEMENTED_POLICY == 3
931 #define NOTIMPLEMENTED() NOTREACHED()
932 #elif NOTIMPLEMENTED_POLICY == 4
933 #define NOTIMPLEMENTED() LOG(ERROR) << NOTIMPLEMENTED_MSG
934 #elif NOTIMPLEMENTED_POLICY == 5
935 #define NOTIMPLEMENTED() do {\
936 static bool logged_once = false;\
937 LOG_IF(ERROR, !logged_once) << NOTIMPLEMENTED_MSG;\
938 logged_once = true;\
939 } while(0);\
940 EAT_STREAM_PARAMETERS
941 #endif
943 #endif // BASE_LOGGING_H_