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