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