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/macros.h"
18 #include "build/build_config.h"
19
20 //
21 // Optional message capabilities
22 // -----------------------------
23 // Assertion failed messages and fatal errors are displayed in a dialog box
24 // before the application exits. However, running this UI creates a message
25 // loop, which causes application messages to be processed and potentially
26 // dispatched to existing application windows. Since the application is in a
27 // bad state when this assertion dialog is displayed, these messages may not
28 // get processed and hang the dialog, or the application might go crazy.
29 //
30 // Therefore, it can be beneficial to display the error dialog in a separate
31 // process from the main application. When the logging system needs to display
32 // a fatal error dialog box, it will look for a program called
33 // "DebugMessage.exe" in the same directory as the application executable. It
34 // will run this application with the message as the command line, and will
35 // not include the name of the application as is traditional for easier
36 // parsing.
37 //
38 // The code for DebugMessage.exe is only one line. In WinMain, do:
39 // MessageBox(NULL, GetCommandLineW(), L"Fatal Error", 0);
40 //
41 // If DebugMessage.exe is not found, the logging code will use a normal
42 // MessageBox, potentially causing the problems discussed above.
43
44
45 // Instructions
46 // ------------
47 //
48 // Make a bunch of macros for logging. The way to log things is to stream
49 // things to LOG(<a particular severity level>). E.g.,
50 //
51 // LOG(INFO) << "Found " << num_cookies << " cookies";
52 //
53 // You can also do conditional logging:
54 //
55 // LOG_IF(INFO, num_cookies > 10) << "Got lots of cookies";
56 //
57 // The CHECK(condition) macro is active in both debug and release builds and
58 // effectively performs a LOG(FATAL) which terminates the process and
59 // generates a crashdump unless a debugger is attached.
60 //
61 // There are also "debug mode" logging macros like the ones above:
62 //
63 // DLOG(INFO) << "Found cookies";
64 //
65 // DLOG_IF(INFO, num_cookies > 10) << "Got lots of cookies";
66 //
67 // All "debug mode" logging is compiled away to nothing for non-debug mode
68 // compiles. LOG_IF and development flags also work well together
69 // because the code can be compiled away sometimes.
70 //
71 // We also have
72 //
73 // LOG_ASSERT(assertion);
74 // DLOG_ASSERT(assertion);
75 //
76 // which is syntactic sugar for {,D}LOG_IF(FATAL, assert fails) << assertion;
77 //
78 // There are "verbose level" logging macros. They look like
79 //
80 // VLOG(1) << "I'm printed when you run the program with --v=1 or more";
81 // VLOG(2) << "I'm printed when you run the program with --v=2 or more";
82 //
83 // These always log at the INFO log level (when they log at all).
84 // The verbose logging can also be turned on module-by-module. For instance,
85 // --vmodule=profile=2,icon_loader=1,browser_*=3,*/chromeos/*=4 --v=0
86 // will cause:
87 // a. VLOG(2) and lower messages to be printed from profile.{h,cc}
88 // b. VLOG(1) and lower messages to be printed from icon_loader.{h,cc}
89 // c. VLOG(3) and lower messages to be printed from files prefixed with
90 // "browser"
91 // d. VLOG(4) and lower messages to be printed from files under a
92 // "chromeos" directory.
93 // e. VLOG(0) and lower messages to be printed from elsewhere
94 //
95 // The wildcarding functionality shown by (c) supports both '*' (match
96 // 0 or more characters) and '?' (match any single character)
97 // wildcards. Any pattern containing a forward or backward slash will
98 // be tested against the whole pathname and not just the module.
99 // E.g., "*/foo/bar/*=2" would change the logging level for all code
100 // in source files under a "foo/bar" directory.
101 //
102 // There's also VLOG_IS_ON(n) "verbose level" condition macro. To be used as
103 //
104 // if (VLOG_IS_ON(2)) {
105 // // do some logging preparation and logging
106 // // that can't be accomplished with just VLOG(2) << ...;
107 // }
108 //
109 // There is also a VLOG_IF "verbose level" condition macro for sample
110 // cases, when some extra computation and preparation for logs is not
111 // needed.
112 //
113 // VLOG_IF(1, (size > 1024))
114 // << "I'm printed when size is more than 1024 and when you run the "
115 // "program with --v=1 or more";
116 //
117 // We also override the standard 'assert' to use 'DLOG_ASSERT'.
118 //
119 // The supported severity levels for macros that allow you to specify one
120 // are (in increasing order of severity) INFO, WARNING, ERROR, and FATAL.
121 //
122 // Very important: logging a message at the FATAL severity level causes
123 // the program to terminate (after the message is logged).
124 //
125 // There is the special severity of DFATAL, which logs FATAL in debug mode,
126 // ERROR in normal mode.
127
128 // Note that "The behavior of a C++ program is undefined if it adds declarations
129 // or definitions to namespace std or to a namespace within namespace std unless
130 // otherwise specified." --C++11[namespace.std]
131 //
132 // We've checked that this particular definition has the intended behavior on
133 // our implementations, but it's prone to breaking in the future, and please
134 // don't imitate this in your own definitions without checking with some
135 // standard library experts.
136 namespace std {
137 // These functions are provided as a convenience for logging, which is where we
138 // use streams (it is against Google style to use streams in other places). It
139 // is designed to allow you to emit non-ASCII Unicode strings to the log file,
140 // which is normally ASCII. It is relatively slow, so try not to use it for
141 // common cases. Non-ASCII characters will be converted to UTF-8 by these
142 // operators.
143 BASE_EXPORT std::ostream& operator<<(std::ostream& out, const wchar_t* wstr);
144 inline std::ostream& operator<<(std::ostream& out, const std::wstring& wstr) {
145 return out << wstr.c_str();
146 }
147
148 template<typename T>
149 typename std::enable_if<std::is_enum<T>::value, std::ostream&>::type operator<<(
150 std::ostream& out, T value) {
151 return out << static_cast<typename std::underlying_type<T>::type>(value);
152 }
153
154 } // namespace std
155
156 namespace logging {
157
158 // Where to record logging output? A flat file and/or system debug log
159 // via OutputDebugString.
160 enum LoggingDestination {
161 LOG_NONE = 0,
162 LOG_TO_SYSTEM_DEBUG_LOG = 1 << 1,
163
164 LOG_TO_ALL = LOG_TO_SYSTEM_DEBUG_LOG,
165
166 LOG_DEFAULT = LOG_TO_SYSTEM_DEBUG_LOG,
167 };
168
169 struct BASE_EXPORT LoggingSettings {
170 // The defaults values are:
171 //
172 // logging_dest: LOG_DEFAULT
173 LoggingSettings();
174
175 LoggingDestination logging_dest;
176 };
177
178 // Define different names for the BaseInitLoggingImpl() function depending on
179 // whether NDEBUG is defined or not so that we'll fail to link if someone tries
180 // to compile logging.cc with NDEBUG but includes logging.h without defining it,
181 // or vice versa.
182 #if NDEBUG
183 #define BaseInitLoggingImpl BaseInitLoggingImpl_built_with_NDEBUG
184 #else
185 #define BaseInitLoggingImpl BaseInitLoggingImpl_built_without_NDEBUG
186 #endif
187
188 // Implementation of the InitLogging() method declared below. We use a
189 // more-specific name so we can #define it above without affecting other code
190 // that has named stuff "InitLogging".
191 BASE_EXPORT bool BaseInitLoggingImpl(const LoggingSettings& settings);
192
193 // Sets the log file name and other global logging state. Calling this function
194 // is recommended, and is normally done at the beginning of application init.
195 // If you don't call it, all the flags will be initialized to their default
196 // values, and there is a race condition that may leak a critical section
197 // object if two threads try to do the first log at the same time.
198 // See the definition of the enums above for descriptions and default values.
199 //
200 // The default log file is initialized to "debug.log" in the application
201 // directory. You probably don't want this, especially since the program
202 // directory may not be writable on an enduser's system.
203 //
204 // This function may be called a second time to re-direct logging (e.g after
205 // loging in to a user partition), however it should never be called more than
206 // twice.
InitLogging(const LoggingSettings & settings)207 inline bool InitLogging(const LoggingSettings& settings) {
208 return BaseInitLoggingImpl(settings);
209 }
210
211 // Sets the log level. Anything at or above this level will be written to the
212 // log file/displayed to the user (if applicable). Anything below this level
213 // will be silently ignored. The log level defaults to 0 (everything is logged
214 // up to level INFO) if this function is not called.
215 // Note that log messages for VLOG(x) are logged at level -x, so setting
216 // the min log level to negative values enables verbose logging.
217 BASE_EXPORT void SetMinLogLevel(int level);
218
219 // Gets the current log level.
220 BASE_EXPORT int GetMinLogLevel();
221
222 // Used by LOG_IS_ON to lazy-evaluate stream arguments.
223 BASE_EXPORT bool ShouldCreateLogMessage(int severity);
224
225 // Gets the VLOG default verbosity level.
226 BASE_EXPORT int GetVlogVerbosity();
227
228 // Gets the current vlog level for the given file (usually taken from
229 // __FILE__).
230
231 // Note that |N| is the size *with* the null terminator.
GetVlogLevelHelper(const char * file_start,size_t N)232 inline int GetVlogLevelHelper(const char* file_start, size_t N) {
233 return GetVlogVerbosity();
234 }
235
236 template <size_t N>
GetVlogLevel(const char (& file)[N])237 int GetVlogLevel(const char (&file)[N]) {
238 return GetVlogLevelHelper(file, N);
239 }
240
241 // Sets the common items you want to be prepended to each log message.
242 // process and thread IDs default to off, the timestamp defaults to on.
243 // If this function is not called, logging defaults to writing the timestamp
244 // only.
245 BASE_EXPORT void SetLogItems(bool enable_process_id,
246 bool enable_thread_id,
247 bool enable_timestamp,
248 bool enable_tickcount);
249
250 // Sets whether or not you'd like to see fatal debug messages popped up in
251 // a dialog box or not.
252 // Dialogs are not shown by default.
253 void SetShowErrorDialogs(bool enable_dialogs);
254
255 // Sets the Log Assert Handler that will be used to notify of check failures.
256 // The default handler shows a dialog box and then terminate the process,
257 // however clients can use this function to override with their own handling
258 // (e.g. a silent one for Unit Tests)
259 typedef void (*LogAssertHandlerFunction)(const std::string& str);
260 BASE_EXPORT void SetLogAssertHandler(LogAssertHandlerFunction handler);
261
262 // Sets the Log Message Handler that gets passed every log message before
263 // it's sent to other log destinations (if any).
264 // Returns true to signal that it handled the message and the message
265 // should not be sent to other log destinations.
266 typedef bool (*LogMessageHandlerFunction)(int severity,
267 const char* file, int line, size_t message_start, const std::string& str);
268 BASE_EXPORT void SetLogMessageHandler(LogMessageHandlerFunction handler);
269 BASE_EXPORT LogMessageHandlerFunction GetLogMessageHandler();
270
271 typedef int LogSeverity;
272 const LogSeverity LOG_VERBOSE = -1; // This is level 1 verbosity
273 // Note: the log severities are used to index into the array of names,
274 // see log_severity_names.
275 const LogSeverity LOG_INFO = 0;
276 const LogSeverity LOG_WARNING = 1;
277 const LogSeverity LOG_ERROR = 2;
278 const LogSeverity LOG_FATAL = 3;
279 const LogSeverity LOG_NUM_SEVERITIES = 4;
280
281 // LOG_DFATAL is LOG_FATAL in debug mode, ERROR in normal mode
282 #ifdef NDEBUG
283 const LogSeverity LOG_DFATAL = LOG_ERROR;
284 #else
285 const LogSeverity LOG_DFATAL = LOG_FATAL;
286 #endif
287
288 // A few definitions of macros that don't generate much code. These are used
289 // by LOG() and LOG_IF, etc. Since these are used all over our code, it's
290 // better to have compact code for these operations.
291 #define COMPACT_GOOGLE_LOG_EX_INFO(ClassName, ...) \
292 logging::ClassName(__FILE__, __LINE__, logging::LOG_INFO , ##__VA_ARGS__)
293 #define COMPACT_GOOGLE_LOG_EX_WARNING(ClassName, ...) \
294 logging::ClassName(__FILE__, __LINE__, logging::LOG_WARNING , ##__VA_ARGS__)
295 #define COMPACT_GOOGLE_LOG_EX_ERROR(ClassName, ...) \
296 logging::ClassName(__FILE__, __LINE__, logging::LOG_ERROR , ##__VA_ARGS__)
297 #define COMPACT_GOOGLE_LOG_EX_FATAL(ClassName, ...) \
298 logging::ClassName(__FILE__, __LINE__, logging::LOG_FATAL , ##__VA_ARGS__)
299 #define COMPACT_GOOGLE_LOG_EX_DFATAL(ClassName, ...) \
300 logging::ClassName(__FILE__, __LINE__, logging::LOG_DFATAL , ##__VA_ARGS__)
301
302 #define COMPACT_GOOGLE_LOG_INFO \
303 COMPACT_GOOGLE_LOG_EX_INFO(LogMessage)
304 #define COMPACT_GOOGLE_LOG_WARNING \
305 COMPACT_GOOGLE_LOG_EX_WARNING(LogMessage)
306 #define COMPACT_GOOGLE_LOG_ERROR \
307 COMPACT_GOOGLE_LOG_EX_ERROR(LogMessage)
308 #define COMPACT_GOOGLE_LOG_FATAL \
309 COMPACT_GOOGLE_LOG_EX_FATAL(LogMessage)
310 #define COMPACT_GOOGLE_LOG_DFATAL \
311 COMPACT_GOOGLE_LOG_EX_DFATAL(LogMessage)
312
313 // As special cases, we can assume that LOG_IS_ON(FATAL) always holds. Also,
314 // LOG_IS_ON(DFATAL) always holds in debug mode. In particular, CHECK()s will
315 // always fire if they fail.
316 #define LOG_IS_ON(severity) \
317 (::logging::ShouldCreateLogMessage(::logging::LOG_##severity))
318
319 // We can't do any caching tricks with VLOG_IS_ON() like the
320 // google-glog version since it requires GCC extensions. This means
321 // that using the v-logging functions in conjunction with --vmodule
322 // may be slow.
323 #define VLOG_IS_ON(verboselevel) \
324 ((verboselevel) <= ::logging::GetVlogLevel(__FILE__))
325
326 // Helper macro which avoids evaluating the arguments to a stream if
327 // the condition doesn't hold. Condition is evaluated once and only once.
328 #define LAZY_STREAM(stream, condition) \
329 !(condition) ? (void) 0 : ::logging::LogMessageVoidify() & (stream)
330
331 // We use the preprocessor's merging operator, "##", so that, e.g.,
332 // LOG(INFO) becomes the token COMPACT_GOOGLE_LOG_INFO. There's some funny
333 // subtle difference between ostream member streaming functions (e.g.,
334 // ostream::operator<<(int) and ostream non-member streaming functions
335 // (e.g., ::operator<<(ostream&, string&): it turns out that it's
336 // impossible to stream something like a string directly to an unnamed
337 // ostream. We employ a neat hack by calling the stream() member
338 // function of LogMessage which seems to avoid the problem.
339 #define LOG_STREAM(severity) COMPACT_GOOGLE_LOG_ ## severity.stream()
340
341 #define LOG(severity) LAZY_STREAM(LOG_STREAM(severity), LOG_IS_ON(severity))
342 #define LOG_IF(severity, condition) \
343 LAZY_STREAM(LOG_STREAM(severity), LOG_IS_ON(severity) && (condition))
344
345 #define SYSLOG(severity) LOG(severity)
346 #define SYSLOG_IF(severity, condition) LOG_IF(severity, condition)
347
348 // The VLOG macros log with negative verbosities.
349 #define VLOG_STREAM(verbose_level) \
350 logging::LogMessage(__FILE__, __LINE__, -verbose_level).stream()
351
352 #define VLOG(verbose_level) \
353 LAZY_STREAM(VLOG_STREAM(verbose_level), VLOG_IS_ON(verbose_level))
354
355 #define VLOG_IF(verbose_level, condition) \
356 LAZY_STREAM(VLOG_STREAM(verbose_level), \
357 VLOG_IS_ON(verbose_level) && (condition))
358
359 #define LOG_ASSERT(condition) \
360 LOG_IF(FATAL, !(condition)) << "Assert failed: " #condition ". "
361 #define SYSLOG_ASSERT(condition) \
362 SYSLOG_IF(FATAL, !(condition)) << "Assert failed: " #condition ". "
363
364 // The actual stream used isn't important.
365 #define EAT_STREAM_PARAMETERS \
366 true ? (void) 0 : ::logging::LogMessageVoidify() & LOG_STREAM(FATAL)
367
368 // Captures the result of a CHECK_EQ (for example) and facilitates testing as a
369 // boolean.
370 class CheckOpResult {
371 public:
372 // |message| must be null if and only if the check failed.
CheckOpResult(std::string * message)373 CheckOpResult(std::string* message) : message_(message) {}
374 // Returns true if the check succeeded.
375 operator bool() const { return !message_; }
376 // Returns the message.
message()377 std::string* message() { return message_; }
378
379 private:
380 std::string* message_;
381 };
382
383 // CHECK dies with a fatal error if condition is not true. It is *not*
384 // controlled by NDEBUG, so the check will be executed regardless of
385 // compilation mode.
386 //
387 // We make sure CHECK et al. always evaluates their arguments, as
388 // doing CHECK(FunctionWithSideEffect()) is a common idiom.
389
390 #if defined(OFFICIAL_BUILD) && defined(NDEBUG) && !defined(OS_ANDROID)
391
392 // Make all CHECK functions discard their log strings to reduce code
393 // bloat for official release builds (except Android).
394
395 // TODO(akalin): This would be more valuable if there were some way to
396 // remove BreakDebugger() from the backtrace, perhaps by turning it
397 // into a macro (like __debugbreak() on Windows).
398 #define CHECK(condition) \
399 !(condition) ? ::base::debug::BreakDebugger() : EAT_STREAM_PARAMETERS
400
401 #define PCHECK(condition) CHECK(condition)
402
403 #define CHECK_OP(name, op, val1, val2) CHECK((val1) op (val2))
404
405 #else
406
407 // Do as much work as possible out of line to reduce inline code size.
408 #define CHECK(condition) \
409 LAZY_STREAM(logging::LogMessage(__FILE__, __LINE__, #condition).stream(), \
410 !(condition))
411
412 // Helper macro for binary operators.
413 // Don't use this macro directly in your code, use CHECK_EQ et al below.
414 // The 'switch' is used to prevent the 'else' from being ambiguous when the
415 // macro is used in an 'if' clause such as:
416 // if (a == 1)
417 // CHECK_EQ(2, a);
418 #define CHECK_OP(name, op, val1, val2) \
419 switch (0) case 0: default: \
420 if (logging::CheckOpResult true_if_passed = \
421 logging::Check##name##Impl((val1), (val2), \
422 #val1 " " #op " " #val2)) \
423 ; \
424 else \
425 logging::LogMessage(__FILE__, __LINE__, true_if_passed.message()).stream()
426
427 #endif
428
429 // Build the error message string. This is separate from the "Impl"
430 // function template because it is not performance critical and so can
431 // be out of line, while the "Impl" code should be inline. Caller
432 // takes ownership of the returned string.
433 template<class t1, class t2>
MakeCheckOpString(const t1 & v1,const t2 & v2,const char * names)434 std::string* MakeCheckOpString(const t1& v1, const t2& v2, const char* names) {
435 std::ostringstream ss;
436 ss << names << " (" << v1 << " vs. " << v2 << ")";
437 std::string* msg = new std::string(ss.str());
438 return msg;
439 }
440
441 // Commonly used instantiations of MakeCheckOpString<>. Explicitly instantiated
442 // in logging.cc.
443 extern template BASE_EXPORT std::string*
444 MakeCheckOpString<int, int>(const int&, const int&, const char* names);
445 extern template BASE_EXPORT
446 std::string* MakeCheckOpString<unsigned long, unsigned long>(
447 const unsigned long&, const unsigned long&, const char* names);
448 extern template BASE_EXPORT
449 std::string* MakeCheckOpString<unsigned long, unsigned int>(
450 const unsigned long&, const unsigned int&, const char* names);
451 extern template BASE_EXPORT
452 std::string* MakeCheckOpString<unsigned int, unsigned long>(
453 const unsigned int&, const unsigned long&, const char* names);
454 extern template BASE_EXPORT
455 std::string* MakeCheckOpString<std::string, std::string>(
456 const std::string&, const std::string&, const char* name);
457
458 // Helper functions for CHECK_OP macro.
459 // The (int, int) specialization works around the issue that the compiler
460 // will not instantiate the template version of the function on values of
461 // unnamed enum type - see comment below.
462 #define DEFINE_CHECK_OP_IMPL(name, op) \
463 template <class t1, class t2> \
464 inline std::string* Check##name##Impl(const t1& v1, const t2& v2, \
465 const char* names) { \
466 if (v1 op v2) return NULL; \
467 else return MakeCheckOpString(v1, v2, names); \
468 } \
469 inline std::string* Check##name##Impl(int v1, int v2, const char* names) { \
470 if (v1 op v2) return NULL; \
471 else return MakeCheckOpString(v1, v2, names); \
472 }
473 DEFINE_CHECK_OP_IMPL(EQ, ==)
474 DEFINE_CHECK_OP_IMPL(NE, !=)
475 DEFINE_CHECK_OP_IMPL(LE, <=)
476 DEFINE_CHECK_OP_IMPL(LT, < )
477 DEFINE_CHECK_OP_IMPL(GE, >=)
478 DEFINE_CHECK_OP_IMPL(GT, > )
479 #undef DEFINE_CHECK_OP_IMPL
480
481 #define CHECK_EQ(val1, val2) CHECK_OP(EQ, ==, val1, val2)
482 #define CHECK_NE(val1, val2) CHECK_OP(NE, !=, val1, val2)
483 #define CHECK_LE(val1, val2) CHECK_OP(LE, <=, val1, val2)
484 #define CHECK_LT(val1, val2) CHECK_OP(LT, < , val1, val2)
485 #define CHECK_GE(val1, val2) CHECK_OP(GE, >=, val1, val2)
486 #define CHECK_GT(val1, val2) CHECK_OP(GT, > , val1, val2)
487
488 #if defined(NDEBUG)
489 #define ENABLE_DLOG 0
490 #else
491 #define ENABLE_DLOG 1
492 #endif
493
494 #if defined(NDEBUG) && !defined(DCHECK_ALWAYS_ON)
495 #define DCHECK_IS_ON() 0
496 #else
497 #define DCHECK_IS_ON() 1
498 #endif
499
500 // Definitions for DLOG et al.
501
502 #if ENABLE_DLOG
503
504 #define DLOG_IS_ON(severity) LOG_IS_ON(severity)
505 #define DLOG_IF(severity, condition) LOG_IF(severity, condition)
506 #define DLOG_ASSERT(condition) LOG_ASSERT(condition)
507 #define DVLOG_IF(verboselevel, condition) VLOG_IF(verboselevel, condition)
508
509 #else // ENABLE_DLOG
510
511 // If ENABLE_DLOG is off, we want to avoid emitting any references to
512 // |condition| (which may reference a variable defined only if NDEBUG
513 // is not defined). Contrast this with DCHECK et al., which has
514 // different behavior.
515
516 #define DLOG_IS_ON(severity) false
517 #define DLOG_IF(severity, condition) EAT_STREAM_PARAMETERS
518 #define DLOG_ASSERT(condition) EAT_STREAM_PARAMETERS
519 #define DVLOG_IF(verboselevel, condition) EAT_STREAM_PARAMETERS
520
521 #endif // ENABLE_DLOG
522
523 // DEBUG_MODE is for uses like
524 // if (DEBUG_MODE) foo.CheckThatFoo();
525 // instead of
526 // #ifndef NDEBUG
527 // foo.CheckThatFoo();
528 // #endif
529 //
530 // We tie its state to ENABLE_DLOG.
531 enum { DEBUG_MODE = ENABLE_DLOG };
532
533 #undef ENABLE_DLOG
534
535 #define DLOG(severity) \
536 LAZY_STREAM(LOG_STREAM(severity), DLOG_IS_ON(severity))
537
538 #define DVLOG(verboselevel) DVLOG_IF(verboselevel, VLOG_IS_ON(verboselevel))
539
540 // Definitions for DCHECK et al.
541
542 #if DCHECK_IS_ON()
543
544 #define COMPACT_GOOGLE_LOG_EX_DCHECK(ClassName, ...) \
545 COMPACT_GOOGLE_LOG_EX_FATAL(ClassName , ##__VA_ARGS__)
546 #define COMPACT_GOOGLE_LOG_DCHECK COMPACT_GOOGLE_LOG_FATAL
547 const LogSeverity LOG_DCHECK = LOG_FATAL;
548
549 #else // DCHECK_IS_ON()
550
551 // These are just dummy values.
552 #define COMPACT_GOOGLE_LOG_EX_DCHECK(ClassName, ...) \
553 COMPACT_GOOGLE_LOG_EX_INFO(ClassName , ##__VA_ARGS__)
554 #define COMPACT_GOOGLE_LOG_DCHECK COMPACT_GOOGLE_LOG_INFO
555 const LogSeverity LOG_DCHECK = LOG_INFO;
556
557 #endif // DCHECK_IS_ON()
558
559 // DCHECK et al. make sure to reference |condition| regardless of
560 // whether DCHECKs are enabled; this is so that we don't get unused
561 // variable warnings if the only use of a variable is in a DCHECK.
562 // This behavior is different from DLOG_IF et al.
563
564 #define DCHECK(condition) \
565 LAZY_STREAM(LOG_STREAM(DCHECK), DCHECK_IS_ON() ? !(condition) : false) \
566 << "Check failed: " #condition ". "
567
568 // Helper macro for binary operators.
569 // Don't use this macro directly in your code, use DCHECK_EQ et al below.
570 // The 'switch' is used to prevent the 'else' from being ambiguous when the
571 // macro is used in an 'if' clause such as:
572 // if (a == 1)
573 // DCHECK_EQ(2, a);
574 #define DCHECK_OP(name, op, val1, val2) \
575 switch (0) case 0: default: \
576 if (logging::CheckOpResult true_if_passed = \
577 DCHECK_IS_ON() ? \
578 logging::Check##name##Impl((val1), (val2), \
579 #val1 " " #op " " #val2) : nullptr) \
580 ; \
581 else \
582 logging::LogMessage(__FILE__, __LINE__, ::logging::LOG_DCHECK, \
583 true_if_passed.message()).stream()
584
585 // Equality/Inequality checks - compare two values, and log a
586 // LOG_DCHECK message including the two values when the result is not
587 // as expected. The values must have operator<<(ostream, ...)
588 // defined.
589 //
590 // You may append to the error message like so:
591 // DCHECK_NE(1, 2) << ": The world must be ending!";
592 //
593 // We are very careful to ensure that each argument is evaluated exactly
594 // once, and that anything which is legal to pass as a function argument is
595 // legal here. In particular, the arguments may be temporary expressions
596 // which will end up being destroyed at the end of the apparent statement,
597 // for example:
598 // DCHECK_EQ(string("abc")[1], 'b');
599 //
600 // WARNING: These may not compile correctly if one of the arguments is a pointer
601 // and the other is NULL. To work around this, simply static_cast NULL to the
602 // type of the desired pointer.
603
604 #define DCHECK_EQ(val1, val2) DCHECK_OP(EQ, ==, val1, val2)
605 #define DCHECK_NE(val1, val2) DCHECK_OP(NE, !=, val1, val2)
606 #define DCHECK_LE(val1, val2) DCHECK_OP(LE, <=, val1, val2)
607 #define DCHECK_LT(val1, val2) DCHECK_OP(LT, < , val1, val2)
608 #define DCHECK_GE(val1, val2) DCHECK_OP(GE, >=, val1, val2)
609 #define DCHECK_GT(val1, val2) DCHECK_OP(GT, > , val1, val2)
610
611 #define NOTREACHED() DCHECK(false)
612
613 // Redefine the standard assert to use our nice log files
614 #undef assert
615 #define assert(x) DLOG_ASSERT(x)
616
617 // This class more or less represents a particular log message. You
618 // create an instance of LogMessage and then stream stuff to it.
619 // When you finish streaming to it, ~LogMessage is called and the
620 // full message gets streamed to the appropriate destination.
621 //
622 // You shouldn't actually use LogMessage's constructor to log things,
623 // though. You should use the LOG() macro (and variants thereof)
624 // above.
625 class BASE_EXPORT LogMessage {
626 public:
627 // Used for LOG(severity).
628 LogMessage(const char* file, int line, LogSeverity severity);
629
630 // Used for CHECK(). Implied severity = LOG_FATAL.
631 LogMessage(const char* file, int line, const char* condition);
632
633 // Used for CHECK_EQ(), etc. Takes ownership of the given string.
634 // Implied severity = LOG_FATAL.
635 LogMessage(const char* file, int line, std::string* result);
636
637 // Used for DCHECK_EQ(), etc. Takes ownership of the given string.
638 LogMessage(const char* file, int line, LogSeverity severity,
639 std::string* result);
640
641 ~LogMessage();
642
stream()643 std::ostream& stream() { return stream_; }
644
645 private:
646 void Init(const char* file, int line);
647
648 LogSeverity severity_;
649 std::ostringstream stream_;
650 size_t message_start_; // Offset of the start of the message (past prefix
651 // info).
652 // The file and line information passed in to the constructor.
653 const char* file_;
654 const int line_;
655
656 DISALLOW_COPY_AND_ASSIGN(LogMessage);
657 };
658
659 // A non-macro interface to the log facility; (useful
660 // when the logging level is not a compile-time constant).
LogAtLevel(int log_level,const std::string & msg)661 inline void LogAtLevel(int log_level, const std::string& msg) {
662 LogMessage(__FILE__, __LINE__, log_level).stream() << msg;
663 }
664
665 // This class is used to explicitly ignore values in the conditional
666 // logging macros. This avoids compiler warnings like "value computed
667 // is not used" and "statement has no effect".
668 class LogMessageVoidify {
669 public:
LogMessageVoidify()670 LogMessageVoidify() { }
671 // This has to be an operator with a precedence lower than << but
672 // higher than ?:
673 void operator&(std::ostream&) { }
674 };
675
676 // Async signal safe logging mechanism.
677 BASE_EXPORT void RawLog(int level, const char* message);
678
679 #define RAW_LOG(level, message) logging::RawLog(logging::LOG_ ## level, message)
680
681 #define RAW_CHECK(condition) \
682 do { \
683 if (!(condition)) \
684 logging::RawLog(logging::LOG_FATAL, "Check failed: " #condition "\n"); \
685 } while (0)
686
687
688 } // namespace logging
689
690 // The NOTIMPLEMENTED() macro annotates codepaths which have
691 // not been implemented yet.
692 //
693 // The implementation of this macro is controlled by NOTIMPLEMENTED_POLICY:
694 // 0 -- Do nothing (stripped by compiler)
695 // 1 -- Warn at compile time
696 // 2 -- Fail at compile time
697 // 3 -- Fail at runtime (DCHECK)
698 // 4 -- [default] LOG(ERROR) at runtime
699 // 5 -- LOG(ERROR) at runtime, only once per call-site
700
701 #ifndef NOTIMPLEMENTED_POLICY
702 // Select default policy: LOG(ERROR)
703 #define NOTIMPLEMENTED_POLICY 4
704 #endif
705
706 #if defined(COMPILER_GCC)
707 // On Linux, with GCC, we can use __PRETTY_FUNCTION__ to get the demangled name
708 // of the current function in the NOTIMPLEMENTED message.
709 #define NOTIMPLEMENTED_MSG "Not implemented reached in " << __PRETTY_FUNCTION__
710 #else
711 #define NOTIMPLEMENTED_MSG "NOT IMPLEMENTED"
712 #endif
713
714 #if NOTIMPLEMENTED_POLICY == 0
715 #define NOTIMPLEMENTED() EAT_STREAM_PARAMETERS
716 #elif NOTIMPLEMENTED_POLICY == 1
717 // TODO, figure out how to generate a warning
718 #define NOTIMPLEMENTED() static_assert(false, "NOT_IMPLEMENTED")
719 #elif NOTIMPLEMENTED_POLICY == 2
720 #define NOTIMPLEMENTED() static_assert(false, "NOT_IMPLEMENTED")
721 #elif NOTIMPLEMENTED_POLICY == 3
722 #define NOTIMPLEMENTED() NOTREACHED()
723 #elif NOTIMPLEMENTED_POLICY == 4
724 #define NOTIMPLEMENTED() LOG(ERROR) << NOTIMPLEMENTED_MSG
725 #elif NOTIMPLEMENTED_POLICY == 5
726 #define NOTIMPLEMENTED() do {\
727 static bool logged_once = false;\
728 LOG_IF(ERROR, !logged_once) << NOTIMPLEMENTED_MSG;\
729 logged_once = true;\
730 } while(0);\
731 EAT_STREAM_PARAMETERS
732 #endif
733
734 #endif // BASE_LOGGING_H_
735