Don't add -fuse-ld=gold to cflags
[chromium-blink-merge.git] / base / logging.h
blobdd17bcedb8ed72e6a55c4400c90112a170f58f43
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 output 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 struct BASE_EXPORT LoggingSettings {
185 // The defaults values are:
187 // logging_dest: LOG_DEFAULT
188 // log_file: NULL
189 // lock_log: LOCK_LOG_FILE
190 // delete_old: APPEND_TO_OLD_LOG_FILE
191 LoggingSettings();
193 LoggingDestination logging_dest;
195 // The three settings below have an effect only when LOG_TO_FILE is
196 // set in |logging_dest|.
197 const PathChar* log_file;
198 LogLockingState lock_log;
199 OldFileDeletionState delete_old;
202 // Define different names for the BaseInitLoggingImpl() function depending on
203 // whether NDEBUG is defined or not so that we'll fail to link if someone tries
204 // to compile logging.cc with NDEBUG but includes logging.h without defining it,
205 // or vice versa.
206 #if NDEBUG
207 #define BaseInitLoggingImpl BaseInitLoggingImpl_built_with_NDEBUG
208 #else
209 #define BaseInitLoggingImpl BaseInitLoggingImpl_built_without_NDEBUG
210 #endif
212 // Implementation of the InitLogging() method declared below. We use a
213 // more-specific name so we can #define it above without affecting other code
214 // that has named stuff "InitLogging".
215 BASE_EXPORT bool BaseInitLoggingImpl(const LoggingSettings& settings);
217 // Sets the log file name and other global logging state. Calling this function
218 // is recommended, and is normally done at the beginning of application init.
219 // If you don't call it, all the flags will be initialized to their default
220 // values, and there is a race condition that may leak a critical section
221 // object if two threads try to do the first log at the same time.
222 // See the definition of the enums above for descriptions and default values.
224 // The default log file is initialized to "debug.log" in the application
225 // directory. You probably don't want this, especially since the program
226 // directory may not be writable on an enduser's system.
228 // This function may be called a second time to re-direct logging (e.g after
229 // loging in to a user partition), however it should never be called more than
230 // twice.
231 inline bool InitLogging(const LoggingSettings& settings) {
232 return BaseInitLoggingImpl(settings);
235 // Sets the log level. Anything at or above this level will be written to the
236 // log file/displayed to the user (if applicable). Anything below this level
237 // will be silently ignored. The log level defaults to 0 (everything is logged
238 // up to level INFO) if this function is not called.
239 // Note that log messages for VLOG(x) are logged at level -x, so setting
240 // the min log level to negative values enables verbose logging.
241 BASE_EXPORT void SetMinLogLevel(int level);
243 // Gets the current log level.
244 BASE_EXPORT int GetMinLogLevel();
246 // Gets the VLOG default verbosity level.
247 BASE_EXPORT int GetVlogVerbosity();
249 // Gets the current vlog level for the given file (usually taken from
250 // __FILE__).
252 // Note that |N| is the size *with* the null terminator.
253 BASE_EXPORT int GetVlogLevelHelper(const char* file_start, size_t N);
255 template <size_t N>
256 int GetVlogLevel(const char (&file)[N]) {
257 return GetVlogLevelHelper(file, N);
260 // Sets the common items you want to be prepended to each log message.
261 // process and thread IDs default to off, the timestamp defaults to on.
262 // If this function is not called, logging defaults to writing the timestamp
263 // only.
264 BASE_EXPORT void SetLogItems(bool enable_process_id, bool enable_thread_id,
265 bool enable_timestamp, bool enable_tickcount);
267 // Sets whether or not you'd like to see fatal debug messages popped up in
268 // a dialog box or not.
269 // Dialogs are not shown by default.
270 BASE_EXPORT void SetShowErrorDialogs(bool enable_dialogs);
272 // Sets the Log Assert Handler that will be used to notify of check failures.
273 // The default handler shows a dialog box and then terminate the process,
274 // however clients can use this function to override with their own handling
275 // (e.g. a silent one for Unit Tests)
276 typedef void (*LogAssertHandlerFunction)(const std::string& str);
277 BASE_EXPORT void SetLogAssertHandler(LogAssertHandlerFunction handler);
279 // Sets the Log Report Handler that will be used to notify of check failures
280 // in non-debug mode. The default handler shows a dialog box and continues
281 // the execution, however clients can use this function to override with their
282 // own handling.
283 typedef void (*LogReportHandlerFunction)(const std::string& str);
284 BASE_EXPORT void SetLogReportHandler(LogReportHandlerFunction handler);
286 // Sets the Log Message Handler that gets passed every log message before
287 // it's sent to other log destinations (if any).
288 // Returns true to signal that it handled the message and the message
289 // should not be sent to other log destinations.
290 typedef bool (*LogMessageHandlerFunction)(int severity,
291 const char* file, int line, size_t message_start, const std::string& str);
292 BASE_EXPORT void SetLogMessageHandler(LogMessageHandlerFunction handler);
293 BASE_EXPORT LogMessageHandlerFunction GetLogMessageHandler();
295 typedef int LogSeverity;
296 const LogSeverity LOG_VERBOSE = -1; // This is level 1 verbosity
297 // Note: the log severities are used to index into the array of names,
298 // see log_severity_names.
299 const LogSeverity LOG_INFO = 0;
300 const LogSeverity LOG_WARNING = 1;
301 const LogSeverity LOG_ERROR = 2;
302 const LogSeverity LOG_ERROR_REPORT = 3;
303 const LogSeverity LOG_FATAL = 4;
304 const LogSeverity LOG_NUM_SEVERITIES = 5;
306 // LOG_DFATAL is LOG_FATAL in debug mode, ERROR in normal mode
307 #ifdef NDEBUG
308 const LogSeverity LOG_DFATAL = LOG_ERROR;
309 #else
310 const LogSeverity LOG_DFATAL = LOG_FATAL;
311 #endif
313 // A few definitions of macros that don't generate much code. These are used
314 // by LOG() and LOG_IF, etc. Since these are used all over our code, it's
315 // better to have compact code for these operations.
316 #define COMPACT_GOOGLE_LOG_EX_INFO(ClassName, ...) \
317 logging::ClassName(__FILE__, __LINE__, logging::LOG_INFO , ##__VA_ARGS__)
318 #define COMPACT_GOOGLE_LOG_EX_WARNING(ClassName, ...) \
319 logging::ClassName(__FILE__, __LINE__, logging::LOG_WARNING , ##__VA_ARGS__)
320 #define COMPACT_GOOGLE_LOG_EX_ERROR(ClassName, ...) \
321 logging::ClassName(__FILE__, __LINE__, logging::LOG_ERROR , ##__VA_ARGS__)
322 #define COMPACT_GOOGLE_LOG_EX_ERROR_REPORT(ClassName, ...) \
323 logging::ClassName(__FILE__, __LINE__, \
324 logging::LOG_ERROR_REPORT , ##__VA_ARGS__)
325 #define COMPACT_GOOGLE_LOG_EX_FATAL(ClassName, ...) \
326 logging::ClassName(__FILE__, __LINE__, logging::LOG_FATAL , ##__VA_ARGS__)
327 #define COMPACT_GOOGLE_LOG_EX_DFATAL(ClassName, ...) \
328 logging::ClassName(__FILE__, __LINE__, logging::LOG_DFATAL , ##__VA_ARGS__)
330 #define COMPACT_GOOGLE_LOG_INFO \
331 COMPACT_GOOGLE_LOG_EX_INFO(LogMessage)
332 #define COMPACT_GOOGLE_LOG_WARNING \
333 COMPACT_GOOGLE_LOG_EX_WARNING(LogMessage)
334 #define COMPACT_GOOGLE_LOG_ERROR \
335 COMPACT_GOOGLE_LOG_EX_ERROR(LogMessage)
336 #define COMPACT_GOOGLE_LOG_ERROR_REPORT \
337 COMPACT_GOOGLE_LOG_EX_ERROR_REPORT(LogMessage)
338 #define COMPACT_GOOGLE_LOG_FATAL \
339 COMPACT_GOOGLE_LOG_EX_FATAL(LogMessage)
340 #define COMPACT_GOOGLE_LOG_DFATAL \
341 COMPACT_GOOGLE_LOG_EX_DFATAL(LogMessage)
343 #if defined(OS_WIN)
344 // wingdi.h defines ERROR to be 0. When we call LOG(ERROR), it gets
345 // substituted with 0, and it expands to COMPACT_GOOGLE_LOG_0. To allow us
346 // to keep using this syntax, we define this macro to do the same thing
347 // as COMPACT_GOOGLE_LOG_ERROR, and also define ERROR the same way that
348 // the Windows SDK does for consistency.
349 #define ERROR 0
350 #define COMPACT_GOOGLE_LOG_EX_0(ClassName, ...) \
351 COMPACT_GOOGLE_LOG_EX_ERROR(ClassName , ##__VA_ARGS__)
352 #define COMPACT_GOOGLE_LOG_0 COMPACT_GOOGLE_LOG_ERROR
353 // Needed for LOG_IS_ON(ERROR).
354 const LogSeverity LOG_0 = LOG_ERROR;
355 #endif
357 // As special cases, we can assume that LOG_IS_ON(ERROR_REPORT) and
358 // LOG_IS_ON(FATAL) always hold. Also, LOG_IS_ON(DFATAL) always holds
359 // in debug mode. In particular, CHECK()s will always fire if they
360 // fail.
361 #define LOG_IS_ON(severity) \
362 ((::logging::LOG_ ## severity) >= ::logging::GetMinLogLevel())
364 // We can't do any caching tricks with VLOG_IS_ON() like the
365 // google-glog version since it requires GCC extensions. This means
366 // that using the v-logging functions in conjunction with --vmodule
367 // may be slow.
368 #define VLOG_IS_ON(verboselevel) \
369 ((verboselevel) <= ::logging::GetVlogLevel(__FILE__))
371 // Helper macro which avoids evaluating the arguments to a stream if
372 // the condition doesn't hold.
373 #define LAZY_STREAM(stream, condition) \
374 !(condition) ? (void) 0 : ::logging::LogMessageVoidify() & (stream)
376 // We use the preprocessor's merging operator, "##", so that, e.g.,
377 // LOG(INFO) becomes the token COMPACT_GOOGLE_LOG_INFO. There's some funny
378 // subtle difference between ostream member streaming functions (e.g.,
379 // ostream::operator<<(int) and ostream non-member streaming functions
380 // (e.g., ::operator<<(ostream&, string&): it turns out that it's
381 // impossible to stream something like a string directly to an unnamed
382 // ostream. We employ a neat hack by calling the stream() member
383 // function of LogMessage which seems to avoid the problem.
384 #define LOG_STREAM(severity) COMPACT_GOOGLE_LOG_ ## severity.stream()
386 #define LOG(severity) LAZY_STREAM(LOG_STREAM(severity), LOG_IS_ON(severity))
387 #define LOG_IF(severity, condition) \
388 LAZY_STREAM(LOG_STREAM(severity), LOG_IS_ON(severity) && (condition))
390 #define SYSLOG(severity) LOG(severity)
391 #define SYSLOG_IF(severity, condition) LOG_IF(severity, condition)
393 // The VLOG macros log with negative verbosities.
394 #define VLOG_STREAM(verbose_level) \
395 logging::LogMessage(__FILE__, __LINE__, -verbose_level).stream()
397 #define VLOG(verbose_level) \
398 LAZY_STREAM(VLOG_STREAM(verbose_level), VLOG_IS_ON(verbose_level))
400 #define VLOG_IF(verbose_level, condition) \
401 LAZY_STREAM(VLOG_STREAM(verbose_level), \
402 VLOG_IS_ON(verbose_level) && (condition))
404 #if defined (OS_WIN)
405 #define VPLOG_STREAM(verbose_level) \
406 logging::Win32ErrorLogMessage(__FILE__, __LINE__, -verbose_level, \
407 ::logging::GetLastSystemErrorCode()).stream()
408 #elif defined(OS_POSIX)
409 #define VPLOG_STREAM(verbose_level) \
410 logging::ErrnoLogMessage(__FILE__, __LINE__, -verbose_level, \
411 ::logging::GetLastSystemErrorCode()).stream()
412 #endif
414 #define VPLOG(verbose_level) \
415 LAZY_STREAM(VPLOG_STREAM(verbose_level), VLOG_IS_ON(verbose_level))
417 #define VPLOG_IF(verbose_level, condition) \
418 LAZY_STREAM(VPLOG_STREAM(verbose_level), \
419 VLOG_IS_ON(verbose_level) && (condition))
421 // TODO(akalin): Add more VLOG variants, e.g. VPLOG.
423 #define LOG_ASSERT(condition) \
424 LOG_IF(FATAL, !(condition)) << "Assert failed: " #condition ". "
425 #define SYSLOG_ASSERT(condition) \
426 SYSLOG_IF(FATAL, !(condition)) << "Assert failed: " #condition ". "
428 #if defined(OS_WIN)
429 #define PLOG_STREAM(severity) \
430 COMPACT_GOOGLE_LOG_EX_ ## severity(Win32ErrorLogMessage, \
431 ::logging::GetLastSystemErrorCode()).stream()
432 #elif defined(OS_POSIX)
433 #define PLOG_STREAM(severity) \
434 COMPACT_GOOGLE_LOG_EX_ ## severity(ErrnoLogMessage, \
435 ::logging::GetLastSystemErrorCode()).stream()
436 #endif
438 #define PLOG(severity) \
439 LAZY_STREAM(PLOG_STREAM(severity), LOG_IS_ON(severity))
441 #define PLOG_IF(severity, condition) \
442 LAZY_STREAM(PLOG_STREAM(severity), LOG_IS_ON(severity) && (condition))
444 // The actual stream used isn't important.
445 #define EAT_STREAM_PARAMETERS \
446 true ? (void) 0 : ::logging::LogMessageVoidify() & LOG_STREAM(FATAL)
448 // CHECK dies with a fatal error if condition is not true. It is *not*
449 // controlled by NDEBUG, so the check will be executed regardless of
450 // compilation mode.
452 // We make sure CHECK et al. always evaluates their arguments, as
453 // doing CHECK(FunctionWithSideEffect()) is a common idiom.
455 #if defined(OFFICIAL_BUILD) && defined(NDEBUG)
457 // Make all CHECK functions discard their log strings to reduce code
458 // bloat for official release builds.
460 // TODO(akalin): This would be more valuable if there were some way to
461 // remove BreakDebugger() from the backtrace, perhaps by turning it
462 // into a macro (like __debugbreak() on Windows).
463 #define CHECK(condition) \
464 !(condition) ? ::base::debug::BreakDebugger() : EAT_STREAM_PARAMETERS
466 #define PCHECK(condition) CHECK(condition)
468 #define CHECK_OP(name, op, val1, val2) CHECK((val1) op (val2))
470 #else
472 #define CHECK(condition) \
473 LAZY_STREAM(LOG_STREAM(FATAL), !(condition)) \
474 << "Check failed: " #condition ". "
476 #define PCHECK(condition) \
477 LAZY_STREAM(PLOG_STREAM(FATAL), !(condition)) \
478 << "Check failed: " #condition ". "
480 // Helper macro for binary operators.
481 // Don't use this macro directly in your code, use CHECK_EQ et al below.
483 // TODO(akalin): Rewrite this so that constructs like if (...)
484 // CHECK_EQ(...) else { ... } work properly.
485 #define CHECK_OP(name, op, val1, val2) \
486 if (std::string* _result = \
487 logging::Check##name##Impl((val1), (val2), \
488 #val1 " " #op " " #val2)) \
489 logging::LogMessage(__FILE__, __LINE__, _result).stream()
491 #endif
493 // Build the error message string. This is separate from the "Impl"
494 // function template because it is not performance critical and so can
495 // be out of line, while the "Impl" code should be inline. Caller
496 // takes ownership of the returned string.
497 template<class t1, class t2>
498 std::string* MakeCheckOpString(const t1& v1, const t2& v2, const char* names) {
499 std::ostringstream ss;
500 ss << names << " (" << v1 << " vs. " << v2 << ")";
501 std::string* msg = new std::string(ss.str());
502 return msg;
505 // MSVC doesn't like complex extern templates and DLLs.
506 #if !defined(COMPILER_MSVC)
507 // Commonly used instantiations of MakeCheckOpString<>. Explicitly instantiated
508 // in logging.cc.
509 extern template BASE_EXPORT std::string* MakeCheckOpString<int, int>(
510 const int&, const int&, const char* names);
511 extern template BASE_EXPORT
512 std::string* MakeCheckOpString<unsigned long, unsigned long>(
513 const unsigned long&, const unsigned long&, const char* names);
514 extern template BASE_EXPORT
515 std::string* MakeCheckOpString<unsigned long, unsigned int>(
516 const unsigned long&, const unsigned int&, const char* names);
517 extern template BASE_EXPORT
518 std::string* MakeCheckOpString<unsigned int, unsigned long>(
519 const unsigned int&, const unsigned long&, const char* names);
520 extern template BASE_EXPORT
521 std::string* MakeCheckOpString<std::string, std::string>(
522 const std::string&, const std::string&, const char* name);
523 #endif
525 // Helper functions for CHECK_OP macro.
526 // The (int, int) specialization works around the issue that the compiler
527 // will not instantiate the template version of the function on values of
528 // unnamed enum type - see comment below.
529 #define DEFINE_CHECK_OP_IMPL(name, op) \
530 template <class t1, class t2> \
531 inline std::string* Check##name##Impl(const t1& v1, const t2& v2, \
532 const char* names) { \
533 if (v1 op v2) return NULL; \
534 else return MakeCheckOpString(v1, v2, names); \
536 inline std::string* Check##name##Impl(int v1, int v2, const char* names) { \
537 if (v1 op v2) return NULL; \
538 else return MakeCheckOpString(v1, v2, names); \
540 DEFINE_CHECK_OP_IMPL(EQ, ==)
541 DEFINE_CHECK_OP_IMPL(NE, !=)
542 DEFINE_CHECK_OP_IMPL(LE, <=)
543 DEFINE_CHECK_OP_IMPL(LT, < )
544 DEFINE_CHECK_OP_IMPL(GE, >=)
545 DEFINE_CHECK_OP_IMPL(GT, > )
546 #undef DEFINE_CHECK_OP_IMPL
548 #define CHECK_EQ(val1, val2) CHECK_OP(EQ, ==, val1, val2)
549 #define CHECK_NE(val1, val2) CHECK_OP(NE, !=, val1, val2)
550 #define CHECK_LE(val1, val2) CHECK_OP(LE, <=, val1, val2)
551 #define CHECK_LT(val1, val2) CHECK_OP(LT, < , val1, val2)
552 #define CHECK_GE(val1, val2) CHECK_OP(GE, >=, val1, val2)
553 #define CHECK_GT(val1, val2) CHECK_OP(GT, > , val1, val2)
555 #if defined(NDEBUG)
556 #define ENABLE_DLOG 0
557 #else
558 #define ENABLE_DLOG 1
559 #endif
561 #if defined(NDEBUG) && !defined(DCHECK_ALWAYS_ON)
562 #define DCHECK_IS_ON 0
563 #else
564 #define DCHECK_IS_ON 1
565 #endif
567 // Definitions for DLOG et al.
569 #if ENABLE_DLOG
571 #define DLOG_IS_ON(severity) LOG_IS_ON(severity)
572 #define DLOG_IF(severity, condition) LOG_IF(severity, condition)
573 #define DLOG_ASSERT(condition) LOG_ASSERT(condition)
574 #define DPLOG_IF(severity, condition) PLOG_IF(severity, condition)
575 #define DVLOG_IF(verboselevel, condition) VLOG_IF(verboselevel, condition)
576 #define DVPLOG_IF(verboselevel, condition) VPLOG_IF(verboselevel, condition)
578 #else // ENABLE_DLOG
580 // If ENABLE_DLOG is off, we want to avoid emitting any references to
581 // |condition| (which may reference a variable defined only if NDEBUG
582 // is not defined). Contrast this with DCHECK et al., which has
583 // different behavior.
585 #define DLOG_IS_ON(severity) false
586 #define DLOG_IF(severity, condition) EAT_STREAM_PARAMETERS
587 #define DLOG_ASSERT(condition) EAT_STREAM_PARAMETERS
588 #define DPLOG_IF(severity, condition) EAT_STREAM_PARAMETERS
589 #define DVLOG_IF(verboselevel, condition) EAT_STREAM_PARAMETERS
590 #define DVPLOG_IF(verboselevel, condition) EAT_STREAM_PARAMETERS
592 #endif // ENABLE_DLOG
594 // DEBUG_MODE is for uses like
595 // if (DEBUG_MODE) foo.CheckThatFoo();
596 // instead of
597 // #ifndef NDEBUG
598 // foo.CheckThatFoo();
599 // #endif
601 // We tie its state to ENABLE_DLOG.
602 enum { DEBUG_MODE = ENABLE_DLOG };
604 #undef ENABLE_DLOG
606 #define DLOG(severity) \
607 LAZY_STREAM(LOG_STREAM(severity), DLOG_IS_ON(severity))
609 #define DPLOG(severity) \
610 LAZY_STREAM(PLOG_STREAM(severity), DLOG_IS_ON(severity))
612 #define DVLOG(verboselevel) DVLOG_IF(verboselevel, VLOG_IS_ON(verboselevel))
614 #define DVPLOG(verboselevel) DVPLOG_IF(verboselevel, VLOG_IS_ON(verboselevel))
616 // TODO(vitalybuka): following should be removed and replaced with PLOG.
617 #if defined(OS_WIN)
618 #define LOG_GETLASTERROR(severity) PLOG(severity)
619 #define DLOG_GETLASTERROR(severity) DPLOG(severity)
620 #elif defined(OS_POSIX)
621 #define LOG_ERRNO(severity) PLOG(severity)
622 #define DLOG_ERRNO(severity) DPLOG(severity)
623 #endif
625 // Definitions for DCHECK et al.
627 #if DCHECK_IS_ON
629 #define COMPACT_GOOGLE_LOG_EX_DCHECK(ClassName, ...) \
630 COMPACT_GOOGLE_LOG_EX_FATAL(ClassName , ##__VA_ARGS__)
631 #define COMPACT_GOOGLE_LOG_DCHECK COMPACT_GOOGLE_LOG_FATAL
632 const LogSeverity LOG_DCHECK = LOG_FATAL;
634 #else // DCHECK_IS_ON
636 // These are just dummy values.
637 #define COMPACT_GOOGLE_LOG_EX_DCHECK(ClassName, ...) \
638 COMPACT_GOOGLE_LOG_EX_INFO(ClassName , ##__VA_ARGS__)
639 #define COMPACT_GOOGLE_LOG_DCHECK COMPACT_GOOGLE_LOG_INFO
640 const LogSeverity LOG_DCHECK = LOG_INFO;
642 #endif // DCHECK_IS_ON
644 // DCHECK et al. make sure to reference |condition| regardless of
645 // whether DCHECKs are enabled; this is so that we don't get unused
646 // variable warnings if the only use of a variable is in a DCHECK.
647 // This behavior is different from DLOG_IF et al.
649 #define DCHECK(condition) \
650 LAZY_STREAM(LOG_STREAM(DCHECK), DCHECK_IS_ON && !(condition)) \
651 << "Check failed: " #condition ". "
653 #define DPCHECK(condition) \
654 LAZY_STREAM(PLOG_STREAM(DCHECK), DCHECK_IS_ON && !(condition)) \
655 << "Check failed: " #condition ". "
657 // Helper macro for binary operators.
658 // Don't use this macro directly in your code, use DCHECK_EQ et al below.
659 #define DCHECK_OP(name, op, val1, val2) \
660 if (DCHECK_IS_ON) \
661 if (std::string* _result = \
662 logging::Check##name##Impl((val1), (val2), \
663 #val1 " " #op " " #val2)) \
664 logging::LogMessage( \
665 __FILE__, __LINE__, ::logging::LOG_DCHECK, \
666 _result).stream()
668 // Equality/Inequality checks - compare two values, and log a
669 // LOG_DCHECK message including the two values when the result is not
670 // as expected. The values must have operator<<(ostream, ...)
671 // defined.
673 // You may append to the error message like so:
674 // DCHECK_NE(1, 2) << ": The world must be ending!";
676 // We are very careful to ensure that each argument is evaluated exactly
677 // once, and that anything which is legal to pass as a function argument is
678 // legal here. In particular, the arguments may be temporary expressions
679 // which will end up being destroyed at the end of the apparent statement,
680 // for example:
681 // DCHECK_EQ(string("abc")[1], 'b');
683 // WARNING: These may not compile correctly if one of the arguments is a pointer
684 // and the other is NULL. To work around this, simply static_cast NULL to the
685 // type of the desired pointer.
687 #define DCHECK_EQ(val1, val2) DCHECK_OP(EQ, ==, val1, val2)
688 #define DCHECK_NE(val1, val2) DCHECK_OP(NE, !=, val1, val2)
689 #define DCHECK_LE(val1, val2) DCHECK_OP(LE, <=, val1, val2)
690 #define DCHECK_LT(val1, val2) DCHECK_OP(LT, < , val1, val2)
691 #define DCHECK_GE(val1, val2) DCHECK_OP(GE, >=, val1, val2)
692 #define DCHECK_GT(val1, val2) DCHECK_OP(GT, > , val1, val2)
694 #if defined(NDEBUG) && defined(OS_CHROMEOS)
695 #define NOTREACHED() LOG(ERROR) << "NOTREACHED() hit in " << \
696 __FUNCTION__ << ". "
697 #else
698 #define NOTREACHED() DCHECK(false)
699 #endif
701 // Redefine the standard assert to use our nice log files
702 #undef assert
703 #define assert(x) DLOG_ASSERT(x)
705 // This class more or less represents a particular log message. You
706 // create an instance of LogMessage and then stream stuff to it.
707 // When you finish streaming to it, ~LogMessage is called and the
708 // full message gets streamed to the appropriate destination.
710 // You shouldn't actually use LogMessage's constructor to log things,
711 // though. You should use the LOG() macro (and variants thereof)
712 // above.
713 class BASE_EXPORT LogMessage {
714 public:
715 LogMessage(const char* file, int line, LogSeverity severity, int ctr);
717 // Two special constructors that generate reduced amounts of code at
718 // LOG call sites for common cases.
720 // Used for LOG(INFO): Implied are:
721 // severity = LOG_INFO, ctr = 0
723 // Using this constructor instead of the more complex constructor above
724 // saves a couple of bytes per call site.
725 LogMessage(const char* file, int line);
727 // Used for LOG(severity) where severity != INFO. Implied
728 // are: ctr = 0
730 // Using this constructor instead of the more complex constructor above
731 // saves a couple of bytes per call site.
732 LogMessage(const char* file, int line, LogSeverity severity);
734 // A special constructor used for check failures. Takes ownership
735 // of the given string.
736 // Implied severity = LOG_FATAL
737 LogMessage(const char* file, int line, std::string* result);
739 // A special constructor used for check failures, with the option to
740 // specify severity. Takes ownership of the given string.
741 LogMessage(const char* file, int line, LogSeverity severity,
742 std::string* result);
744 ~LogMessage();
746 std::ostream& stream() { return stream_; }
748 private:
749 void Init(const char* file, int line);
751 LogSeverity severity_;
752 std::ostringstream stream_;
753 size_t message_start_; // Offset of the start of the message (past prefix
754 // info).
755 // The file and line information passed in to the constructor.
756 const char* file_;
757 const int line_;
759 #if defined(OS_WIN)
760 // Stores the current value of GetLastError in the constructor and restores
761 // it in the destructor by calling SetLastError.
762 // This is useful since the LogMessage class uses a lot of Win32 calls
763 // that will lose the value of GLE and the code that called the log function
764 // will have lost the thread error value when the log call returns.
765 class SaveLastError {
766 public:
767 SaveLastError();
768 ~SaveLastError();
770 unsigned long get_error() const { return last_error_; }
772 protected:
773 unsigned long last_error_;
776 SaveLastError last_error_;
777 #endif
779 DISALLOW_COPY_AND_ASSIGN(LogMessage);
782 // A non-macro interface to the log facility; (useful
783 // when the logging level is not a compile-time constant).
784 inline void LogAtLevel(int const log_level, std::string const &msg) {
785 LogMessage(__FILE__, __LINE__, log_level).stream() << msg;
788 // This class is used to explicitly ignore values in the conditional
789 // logging macros. This avoids compiler warnings like "value computed
790 // is not used" and "statement has no effect".
791 class LogMessageVoidify {
792 public:
793 LogMessageVoidify() { }
794 // This has to be an operator with a precedence lower than << but
795 // higher than ?:
796 void operator&(std::ostream&) { }
799 #if defined(OS_WIN)
800 typedef unsigned long SystemErrorCode;
801 #elif defined(OS_POSIX)
802 typedef int SystemErrorCode;
803 #endif
805 // Alias for ::GetLastError() on Windows and errno on POSIX. Avoids having to
806 // pull in windows.h just for GetLastError() and DWORD.
807 BASE_EXPORT SystemErrorCode GetLastSystemErrorCode();
808 BASE_EXPORT std::string SystemErrorCodeToString(SystemErrorCode error_code);
810 #if defined(OS_WIN)
811 // Appends a formatted system message of the GetLastError() type.
812 class BASE_EXPORT Win32ErrorLogMessage {
813 public:
814 Win32ErrorLogMessage(const char* file,
815 int line,
816 LogSeverity severity,
817 SystemErrorCode err);
819 // Appends the error message before destructing the encapsulated class.
820 ~Win32ErrorLogMessage();
822 std::ostream& stream() { return log_message_.stream(); }
824 private:
825 SystemErrorCode err_;
826 LogMessage log_message_;
828 DISALLOW_COPY_AND_ASSIGN(Win32ErrorLogMessage);
830 #elif defined(OS_POSIX)
831 // Appends a formatted system message of the errno type
832 class BASE_EXPORT ErrnoLogMessage {
833 public:
834 ErrnoLogMessage(const char* file,
835 int line,
836 LogSeverity severity,
837 SystemErrorCode err);
839 // Appends the error message before destructing the encapsulated class.
840 ~ErrnoLogMessage();
842 std::ostream& stream() { return log_message_.stream(); }
844 private:
845 SystemErrorCode err_;
846 LogMessage log_message_;
848 DISALLOW_COPY_AND_ASSIGN(ErrnoLogMessage);
850 #endif // OS_WIN
852 // Closes the log file explicitly if open.
853 // NOTE: Since the log file is opened as necessary by the action of logging
854 // statements, there's no guarantee that it will stay closed
855 // after this call.
856 BASE_EXPORT void CloseLogFile();
858 // Async signal safe logging mechanism.
859 BASE_EXPORT void RawLog(int level, const char* message);
861 #define RAW_LOG(level, message) logging::RawLog(logging::LOG_ ## level, message)
863 #define RAW_CHECK(condition) \
864 do { \
865 if (!(condition)) \
866 logging::RawLog(logging::LOG_FATAL, "Check failed: " #condition "\n"); \
867 } while (0)
869 #if defined(OS_WIN)
870 // Returns the default log file path.
871 BASE_EXPORT std::wstring GetLogFileFullPath();
872 #endif
874 } // namespace logging
876 // These functions are provided as a convenience for logging, which is where we
877 // use streams (it is against Google style to use streams in other places). It
878 // is designed to allow you to emit non-ASCII Unicode strings to the log file,
879 // which is normally ASCII. It is relatively slow, so try not to use it for
880 // common cases. Non-ASCII characters will be converted to UTF-8 by these
881 // operators.
882 BASE_EXPORT std::ostream& operator<<(std::ostream& out, const wchar_t* wstr);
883 inline std::ostream& operator<<(std::ostream& out, const std::wstring& wstr) {
884 return out << wstr.c_str();
887 // The NOTIMPLEMENTED() macro annotates codepaths which have
888 // not been implemented yet.
890 // The implementation of this macro is controlled by NOTIMPLEMENTED_POLICY:
891 // 0 -- Do nothing (stripped by compiler)
892 // 1 -- Warn at compile time
893 // 2 -- Fail at compile time
894 // 3 -- Fail at runtime (DCHECK)
895 // 4 -- [default] LOG(ERROR) at runtime
896 // 5 -- LOG(ERROR) at runtime, only once per call-site
898 #ifndef NOTIMPLEMENTED_POLICY
899 #if defined(OS_ANDROID) && defined(OFFICIAL_BUILD)
900 #define NOTIMPLEMENTED_POLICY 0
901 #else
902 // Select default policy: LOG(ERROR)
903 #define NOTIMPLEMENTED_POLICY 4
904 #endif
905 #endif
907 #if defined(COMPILER_GCC)
908 // On Linux, with GCC, we can use __PRETTY_FUNCTION__ to get the demangled name
909 // of the current function in the NOTIMPLEMENTED message.
910 #define NOTIMPLEMENTED_MSG "Not implemented reached in " << __PRETTY_FUNCTION__
911 #else
912 #define NOTIMPLEMENTED_MSG "NOT IMPLEMENTED"
913 #endif
915 #if NOTIMPLEMENTED_POLICY == 0
916 #define NOTIMPLEMENTED() EAT_STREAM_PARAMETERS
917 #elif NOTIMPLEMENTED_POLICY == 1
918 // TODO, figure out how to generate a warning
919 #define NOTIMPLEMENTED() COMPILE_ASSERT(false, NOT_IMPLEMENTED)
920 #elif NOTIMPLEMENTED_POLICY == 2
921 #define NOTIMPLEMENTED() COMPILE_ASSERT(false, NOT_IMPLEMENTED)
922 #elif NOTIMPLEMENTED_POLICY == 3
923 #define NOTIMPLEMENTED() NOTREACHED()
924 #elif NOTIMPLEMENTED_POLICY == 4
925 #define NOTIMPLEMENTED() LOG(ERROR) << NOTIMPLEMENTED_MSG
926 #elif NOTIMPLEMENTED_POLICY == 5
927 #define NOTIMPLEMENTED() do {\
928 static bool logged_once = false;\
929 LOG_IF(ERROR, !logged_once) << NOTIMPLEMENTED_MSG;\
930 logged_once = true;\
931 } while(0);\
932 EAT_STREAM_PARAMETERS
933 #endif
935 #endif // BASE_LOGGING_H_