blob: 1290bfe903d486e73d527fe8fe1754e063a4a507 [file] [log] [blame]
Vitaly Bukacbed2062015-08-17 12:54:05 -07001// 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
Alex Vakulenko674f0eb2016-01-20 08:10:48 -08008#include <stddef.h>
9
Vitaly Bukacbed2062015-08-17 12:54:05 -070010#include <cassert>
Vitaly Bukacbed2062015-08-17 12:54:05 -070011#include <cstring>
12#include <sstream>
Alex Vakulenko674f0eb2016-01-20 08:10:48 -080013#include <string>
14#include <typeinfo>
Vitaly Bukacbed2062015-08-17 12:54:05 -070015
16#include "base/base_export.h"
Alex Vakulenko674f0eb2016-01-20 08:10:48 -080017#include "base/macros.h"
Alex Vakulenkof1fa8be2015-12-08 12:38:56 -080018#include "build/build_config.h"
Vitaly Bukacbed2062015-08-17 12:54:05 -070019
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//
Vitaly Bukacbed2062015-08-17 12:54:05 -0700119// 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
Alex Vakulenko674f0eb2016-01-20 08:10:48 -0800128// 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.
136namespace 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.
143BASE_EXPORT std::ostream& operator<<(std::ostream& out, const wchar_t* wstr);
144inline std::ostream& operator<<(std::ostream& out, const std::wstring& wstr) {
145 return out << wstr.c_str();
146}
147
148template<typename T>
149typename 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
Vitaly Bukacbed2062015-08-17 12:54:05 -0700156namespace logging {
157
Vitaly Bukacbed2062015-08-17 12:54:05 -0700158// Where to record logging output? A flat file and/or system debug log
159// via OutputDebugString.
160enum LoggingDestination {
161 LOG_NONE = 0,
Vitaly Bukacbed2062015-08-17 12:54:05 -0700162 LOG_TO_SYSTEM_DEBUG_LOG = 1 << 1,
163
Vitaly Buka8750b272015-08-18 18:39:08 -0700164 LOG_TO_ALL = LOG_TO_SYSTEM_DEBUG_LOG,
Vitaly Bukacbed2062015-08-17 12:54:05 -0700165
Vitaly Bukacbed2062015-08-17 12:54:05 -0700166 LOG_DEFAULT = LOG_TO_SYSTEM_DEBUG_LOG,
Vitaly Bukacbed2062015-08-17 12:54:05 -0700167};
168
Vitaly Bukacbed2062015-08-17 12:54:05 -0700169struct BASE_EXPORT LoggingSettings {
170 // The defaults values are:
171 //
172 // logging_dest: LOG_DEFAULT
Vitaly Bukacbed2062015-08-17 12:54:05 -0700173 LoggingSettings();
174
175 LoggingDestination logging_dest;
Vitaly Bukacbed2062015-08-17 12:54:05 -0700176};
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".
Vitaly Buka02fe5932015-08-23 12:23:08 -0700191BASE_EXPORT bool BaseInitLoggingImpl(const LoggingSettings& settings);
Vitaly Bukacbed2062015-08-17 12:54:05 -0700192
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.
207inline 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.
217BASE_EXPORT void SetMinLogLevel(int level);
218
219// Gets the current log level.
220BASE_EXPORT int GetMinLogLevel();
221
Alex Vakulenko674f0eb2016-01-20 08:10:48 -0800222// Used by LOG_IS_ON to lazy-evaluate stream arguments.
223BASE_EXPORT bool ShouldCreateLogMessage(int severity);
224
Vitaly Bukacbed2062015-08-17 12:54:05 -0700225// Gets the VLOG default verbosity level.
226BASE_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.
Vitaly Buka890124a2015-10-09 16:18:51 -0700232inline int GetVlogLevelHelper(const char* file_start, size_t N) {
233 return GetVlogVerbosity();
234}
Vitaly Bukacbed2062015-08-17 12:54:05 -0700235
236template <size_t N>
237int 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.
Vitaly Buka60b8f002015-08-20 13:47:48 -0700245BASE_EXPORT void SetLogItems(bool enable_process_id,
246 bool enable_thread_id,
247 bool enable_timestamp,
248 bool enable_tickcount);
Vitaly Bukacbed2062015-08-17 12:54:05 -0700249
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.
Vitaly Buka60b8f002015-08-20 13:47:48 -0700253void SetShowErrorDialogs(bool enable_dialogs);
Vitaly Bukacbed2062015-08-17 12:54:05 -0700254
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)
259typedef void (*LogAssertHandlerFunction)(const std::string& str);
260BASE_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.
266typedef bool (*LogMessageHandlerFunction)(int severity,
267 const char* file, int line, size_t message_start, const std::string& str);
268BASE_EXPORT void SetLogMessageHandler(LogMessageHandlerFunction handler);
269BASE_EXPORT LogMessageHandlerFunction GetLogMessageHandler();
270
271typedef int LogSeverity;
272const 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.
275const LogSeverity LOG_INFO = 0;
276const LogSeverity LOG_WARNING = 1;
277const LogSeverity LOG_ERROR = 2;
278const LogSeverity LOG_FATAL = 3;
279const LogSeverity LOG_NUM_SEVERITIES = 4;
280
281// LOG_DFATAL is LOG_FATAL in debug mode, ERROR in normal mode
282#ifdef NDEBUG
283const LogSeverity LOG_DFATAL = LOG_ERROR;
284#else
285const 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
Vitaly Bukacbed2062015-08-17 12:54:05 -0700313// 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) \
Alex Vakulenko674f0eb2016-01-20 08:10:48 -0800317 (::logging::ShouldCreateLogMessage(::logging::LOG_##severity))
Vitaly Bukacbed2062015-08-17 12:54:05 -0700318
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
Vitaly Bukacbed2062015-08-17 12:54:05 -0700345// The VLOG macros log with negative verbosities.
346#define VLOG_STREAM(verbose_level) \
347 logging::LogMessage(__FILE__, __LINE__, -verbose_level).stream()
348
349#define VLOG(verbose_level) \
350 LAZY_STREAM(VLOG_STREAM(verbose_level), VLOG_IS_ON(verbose_level))
351
352#define VLOG_IF(verbose_level, condition) \
353 LAZY_STREAM(VLOG_STREAM(verbose_level), \
354 VLOG_IS_ON(verbose_level) && (condition))
355
Vitaly Bukacbed2062015-08-17 12:54:05 -0700356#define LOG_ASSERT(condition) \
357 LOG_IF(FATAL, !(condition)) << "Assert failed: " #condition ". "
Vitaly Bukacbed2062015-08-17 12:54:05 -0700358
Vitaly Bukacbed2062015-08-17 12:54:05 -0700359// The actual stream used isn't important.
360#define EAT_STREAM_PARAMETERS \
361 true ? (void) 0 : ::logging::LogMessageVoidify() & LOG_STREAM(FATAL)
362
Alex Vakulenko674f0eb2016-01-20 08:10:48 -0800363// Captures the result of a CHECK_EQ (for example) and facilitates testing as a
364// boolean.
365class CheckOpResult {
366 public:
367 // |message| must be null if and only if the check failed.
368 CheckOpResult(std::string* message) : message_(message) {}
369 // Returns true if the check succeeded.
370 operator bool() const { return !message_; }
371 // Returns the message.
372 std::string* message() { return message_; }
373
374 private:
375 std::string* message_;
376};
377
Vitaly Bukacbed2062015-08-17 12:54:05 -0700378// CHECK dies with a fatal error if condition is not true. It is *not*
379// controlled by NDEBUG, so the check will be executed regardless of
380// compilation mode.
381//
382// We make sure CHECK et al. always evaluates their arguments, as
383// doing CHECK(FunctionWithSideEffect()) is a common idiom.
384
385#if defined(OFFICIAL_BUILD) && defined(NDEBUG) && !defined(OS_ANDROID)
386
387// Make all CHECK functions discard their log strings to reduce code
Alex Vakulenko674f0eb2016-01-20 08:10:48 -0800388// bloat for official release builds (except Android).
Vitaly Bukacbed2062015-08-17 12:54:05 -0700389
390// TODO(akalin): This would be more valuable if there were some way to
391// remove BreakDebugger() from the backtrace, perhaps by turning it
392// into a macro (like __debugbreak() on Windows).
393#define CHECK(condition) \
394 !(condition) ? ::base::debug::BreakDebugger() : EAT_STREAM_PARAMETERS
395
396#define PCHECK(condition) CHECK(condition)
397
398#define CHECK_OP(name, op, val1, val2) CHECK((val1) op (val2))
399
400#else
401
Alex Vakulenko674f0eb2016-01-20 08:10:48 -0800402// Do as much work as possible out of line to reduce inline code size.
403#define CHECK(condition) \
404 LAZY_STREAM(logging::LogMessage(__FILE__, __LINE__, #condition).stream(), \
405 !(condition))
Vitaly Bukacbed2062015-08-17 12:54:05 -0700406
Vitaly Bukacbed2062015-08-17 12:54:05 -0700407// Helper macro for binary operators.
408// Don't use this macro directly in your code, use CHECK_EQ et al below.
Alex Vakulenko674f0eb2016-01-20 08:10:48 -0800409// The 'switch' is used to prevent the 'else' from being ambiguous when the
410// macro is used in an 'if' clause such as:
411// if (a == 1)
412// CHECK_EQ(2, a);
413#define CHECK_OP(name, op, val1, val2) \
414 switch (0) case 0: default: \
415 if (logging::CheckOpResult true_if_passed = \
416 logging::Check##name##Impl((val1), (val2), \
417 #val1 " " #op " " #val2)) \
418 ; \
419 else \
420 logging::LogMessage(__FILE__, __LINE__, true_if_passed.message()).stream()
Vitaly Bukacbed2062015-08-17 12:54:05 -0700421
422#endif
423
424// Build the error message string. This is separate from the "Impl"
425// function template because it is not performance critical and so can
426// be out of line, while the "Impl" code should be inline. Caller
427// takes ownership of the returned string.
428template<class t1, class t2>
429std::string* MakeCheckOpString(const t1& v1, const t2& v2, const char* names) {
430 std::ostringstream ss;
431 ss << names << " (" << v1 << " vs. " << v2 << ")";
432 std::string* msg = new std::string(ss.str());
433 return msg;
434}
435
436// Commonly used instantiations of MakeCheckOpString<>. Explicitly instantiated
437// in logging.cc.
Vitaly Buka60b8f002015-08-20 13:47:48 -0700438extern template BASE_EXPORT std::string*
439MakeCheckOpString<int, int>(const int&, const int&, const char* names);
Vitaly Bukacbed2062015-08-17 12:54:05 -0700440extern template BASE_EXPORT
441std::string* MakeCheckOpString<unsigned long, unsigned long>(
442 const unsigned long&, const unsigned long&, const char* names);
443extern template BASE_EXPORT
444std::string* MakeCheckOpString<unsigned long, unsigned int>(
445 const unsigned long&, const unsigned int&, const char* names);
446extern template BASE_EXPORT
447std::string* MakeCheckOpString<unsigned int, unsigned long>(
448 const unsigned int&, const unsigned long&, const char* names);
449extern template BASE_EXPORT
450std::string* MakeCheckOpString<std::string, std::string>(
451 const std::string&, const std::string&, const char* name);
452
453// Helper functions for CHECK_OP macro.
454// The (int, int) specialization works around the issue that the compiler
455// will not instantiate the template version of the function on values of
456// unnamed enum type - see comment below.
457#define DEFINE_CHECK_OP_IMPL(name, op) \
458 template <class t1, class t2> \
459 inline std::string* Check##name##Impl(const t1& v1, const t2& v2, \
460 const char* names) { \
461 if (v1 op v2) return NULL; \
462 else return MakeCheckOpString(v1, v2, names); \
463 } \
464 inline std::string* Check##name##Impl(int v1, int v2, const char* names) { \
465 if (v1 op v2) return NULL; \
466 else return MakeCheckOpString(v1, v2, names); \
467 }
468DEFINE_CHECK_OP_IMPL(EQ, ==)
469DEFINE_CHECK_OP_IMPL(NE, !=)
470DEFINE_CHECK_OP_IMPL(LE, <=)
471DEFINE_CHECK_OP_IMPL(LT, < )
472DEFINE_CHECK_OP_IMPL(GE, >=)
473DEFINE_CHECK_OP_IMPL(GT, > )
474#undef DEFINE_CHECK_OP_IMPL
475
476#define CHECK_EQ(val1, val2) CHECK_OP(EQ, ==, val1, val2)
477#define CHECK_NE(val1, val2) CHECK_OP(NE, !=, val1, val2)
478#define CHECK_LE(val1, val2) CHECK_OP(LE, <=, val1, val2)
479#define CHECK_LT(val1, val2) CHECK_OP(LT, < , val1, val2)
480#define CHECK_GE(val1, val2) CHECK_OP(GE, >=, val1, val2)
481#define CHECK_GT(val1, val2) CHECK_OP(GT, > , val1, val2)
Vitaly Bukacbed2062015-08-17 12:54:05 -0700482
483#if defined(NDEBUG)
484#define ENABLE_DLOG 0
485#else
486#define ENABLE_DLOG 1
487#endif
488
489#if defined(NDEBUG) && !defined(DCHECK_ALWAYS_ON)
490#define DCHECK_IS_ON() 0
491#else
492#define DCHECK_IS_ON() 1
493#endif
494
495// Definitions for DLOG et al.
496
497#if ENABLE_DLOG
498
499#define DLOG_IS_ON(severity) LOG_IS_ON(severity)
500#define DLOG_IF(severity, condition) LOG_IF(severity, condition)
501#define DLOG_ASSERT(condition) LOG_ASSERT(condition)
Vitaly Bukacbed2062015-08-17 12:54:05 -0700502#define DVLOG_IF(verboselevel, condition) VLOG_IF(verboselevel, condition)
Vitaly Bukacbed2062015-08-17 12:54:05 -0700503
504#else // ENABLE_DLOG
505
506// If ENABLE_DLOG is off, we want to avoid emitting any references to
507// |condition| (which may reference a variable defined only if NDEBUG
508// is not defined). Contrast this with DCHECK et al., which has
509// different behavior.
510
511#define DLOG_IS_ON(severity) false
512#define DLOG_IF(severity, condition) EAT_STREAM_PARAMETERS
513#define DLOG_ASSERT(condition) EAT_STREAM_PARAMETERS
Vitaly Bukacbed2062015-08-17 12:54:05 -0700514#define DVLOG_IF(verboselevel, condition) EAT_STREAM_PARAMETERS
Vitaly Bukacbed2062015-08-17 12:54:05 -0700515
516#endif // ENABLE_DLOG
517
518// DEBUG_MODE is for uses like
519// if (DEBUG_MODE) foo.CheckThatFoo();
520// instead of
521// #ifndef NDEBUG
522// foo.CheckThatFoo();
523// #endif
524//
525// We tie its state to ENABLE_DLOG.
526enum { DEBUG_MODE = ENABLE_DLOG };
527
528#undef ENABLE_DLOG
529
530#define DLOG(severity) \
531 LAZY_STREAM(LOG_STREAM(severity), DLOG_IS_ON(severity))
532
Vitaly Bukacbed2062015-08-17 12:54:05 -0700533#define DVLOG(verboselevel) DVLOG_IF(verboselevel, VLOG_IS_ON(verboselevel))
534
Vitaly Bukacbed2062015-08-17 12:54:05 -0700535// Definitions for DCHECK et al.
536
537#if DCHECK_IS_ON()
538
539#define COMPACT_GOOGLE_LOG_EX_DCHECK(ClassName, ...) \
540 COMPACT_GOOGLE_LOG_EX_FATAL(ClassName , ##__VA_ARGS__)
541#define COMPACT_GOOGLE_LOG_DCHECK COMPACT_GOOGLE_LOG_FATAL
542const LogSeverity LOG_DCHECK = LOG_FATAL;
543
544#else // DCHECK_IS_ON()
545
546// These are just dummy values.
547#define COMPACT_GOOGLE_LOG_EX_DCHECK(ClassName, ...) \
548 COMPACT_GOOGLE_LOG_EX_INFO(ClassName , ##__VA_ARGS__)
549#define COMPACT_GOOGLE_LOG_DCHECK COMPACT_GOOGLE_LOG_INFO
550const LogSeverity LOG_DCHECK = LOG_INFO;
551
552#endif // DCHECK_IS_ON()
553
554// DCHECK et al. make sure to reference |condition| regardless of
555// whether DCHECKs are enabled; this is so that we don't get unused
556// variable warnings if the only use of a variable is in a DCHECK.
557// This behavior is different from DLOG_IF et al.
558
Vitaly Bukacbed2062015-08-17 12:54:05 -0700559#define DCHECK(condition) \
560 LAZY_STREAM(LOG_STREAM(DCHECK), DCHECK_IS_ON() ? !(condition) : false) \
561 << "Check failed: " #condition ". "
562
Vitaly Bukacbed2062015-08-17 12:54:05 -0700563// Helper macro for binary operators.
564// Don't use this macro directly in your code, use DCHECK_EQ et al below.
Alex Vakulenko674f0eb2016-01-20 08:10:48 -0800565// The 'switch' is used to prevent the 'else' from being ambiguous when the
566// macro is used in an 'if' clause such as:
567// if (a == 1)
568// DCHECK_EQ(2, a);
569#define DCHECK_OP(name, op, val1, val2) \
570 switch (0) case 0: default: \
571 if (logging::CheckOpResult true_if_passed = \
572 DCHECK_IS_ON() ? \
573 logging::Check##name##Impl((val1), (val2), \
574 #val1 " " #op " " #val2) : nullptr) \
575 ; \
576 else \
577 logging::LogMessage(__FILE__, __LINE__, ::logging::LOG_DCHECK, \
578 true_if_passed.message()).stream()
Vitaly Bukacbed2062015-08-17 12:54:05 -0700579
580// Equality/Inequality checks - compare two values, and log a
581// LOG_DCHECK message including the two values when the result is not
582// as expected. The values must have operator<<(ostream, ...)
583// defined.
584//
585// You may append to the error message like so:
586// DCHECK_NE(1, 2) << ": The world must be ending!";
587//
588// We are very careful to ensure that each argument is evaluated exactly
589// once, and that anything which is legal to pass as a function argument is
590// legal here. In particular, the arguments may be temporary expressions
591// which will end up being destroyed at the end of the apparent statement,
592// for example:
593// DCHECK_EQ(string("abc")[1], 'b');
594//
595// WARNING: These may not compile correctly if one of the arguments is a pointer
596// and the other is NULL. To work around this, simply static_cast NULL to the
597// type of the desired pointer.
598
599#define DCHECK_EQ(val1, val2) DCHECK_OP(EQ, ==, val1, val2)
600#define DCHECK_NE(val1, val2) DCHECK_OP(NE, !=, val1, val2)
601#define DCHECK_LE(val1, val2) DCHECK_OP(LE, <=, val1, val2)
602#define DCHECK_LT(val1, val2) DCHECK_OP(LT, < , val1, val2)
603#define DCHECK_GE(val1, val2) DCHECK_OP(GE, >=, val1, val2)
604#define DCHECK_GT(val1, val2) DCHECK_OP(GT, > , val1, val2)
Vitaly Bukacbed2062015-08-17 12:54:05 -0700605
Vitaly Bukacbed2062015-08-17 12:54:05 -0700606#define NOTREACHED() DCHECK(false)
Vitaly Bukacbed2062015-08-17 12:54:05 -0700607
608// Redefine the standard assert to use our nice log files
609#undef assert
610#define assert(x) DLOG_ASSERT(x)
611
612// This class more or less represents a particular log message. You
613// create an instance of LogMessage and then stream stuff to it.
614// When you finish streaming to it, ~LogMessage is called and the
615// full message gets streamed to the appropriate destination.
616//
617// You shouldn't actually use LogMessage's constructor to log things,
618// though. You should use the LOG() macro (and variants thereof)
619// above.
620class BASE_EXPORT LogMessage {
621 public:
622 // Used for LOG(severity).
623 LogMessage(const char* file, int line, LogSeverity severity);
624
Alex Vakulenko674f0eb2016-01-20 08:10:48 -0800625 // Used for CHECK(). Implied severity = LOG_FATAL.
626 LogMessage(const char* file, int line, const char* condition);
627
Vitaly Bukacbed2062015-08-17 12:54:05 -0700628 // Used for CHECK_EQ(), etc. Takes ownership of the given string.
629 // Implied severity = LOG_FATAL.
630 LogMessage(const char* file, int line, std::string* result);
631
632 // Used for DCHECK_EQ(), etc. Takes ownership of the given string.
633 LogMessage(const char* file, int line, LogSeverity severity,
634 std::string* result);
635
636 ~LogMessage();
637
638 std::ostream& stream() { return stream_; }
639
640 private:
641 void Init(const char* file, int line);
642
643 LogSeverity severity_;
644 std::ostringstream stream_;
645 size_t message_start_; // Offset of the start of the message (past prefix
646 // info).
647 // The file and line information passed in to the constructor.
648 const char* file_;
649 const int line_;
650
Vitaly Bukacbed2062015-08-17 12:54:05 -0700651 DISALLOW_COPY_AND_ASSIGN(LogMessage);
652};
653
Vitaly Bukacbed2062015-08-17 12:54:05 -0700654// This class is used to explicitly ignore values in the conditional
655// logging macros. This avoids compiler warnings like "value computed
656// is not used" and "statement has no effect".
657class LogMessageVoidify {
658 public:
659 LogMessageVoidify() { }
660 // This has to be an operator with a precedence lower than << but
661 // higher than ?:
662 void operator&(std::ostream&) { }
663};
664
Vitaly Bukacbed2062015-08-17 12:54:05 -0700665// Async signal safe logging mechanism.
666BASE_EXPORT void RawLog(int level, const char* message);
667
668#define RAW_LOG(level, message) logging::RawLog(logging::LOG_ ## level, message)
669
670#define RAW_CHECK(condition) \
671 do { \
672 if (!(condition)) \
673 logging::RawLog(logging::LOG_FATAL, "Check failed: " #condition "\n"); \
674 } while (0)
675
Vitaly Bukacbed2062015-08-17 12:54:05 -0700676
677} // namespace logging
678
Vitaly Bukacbed2062015-08-17 12:54:05 -0700679// The NOTIMPLEMENTED() macro annotates codepaths which have
680// not been implemented yet.
681//
682// The implementation of this macro is controlled by NOTIMPLEMENTED_POLICY:
683// 0 -- Do nothing (stripped by compiler)
684// 1 -- Warn at compile time
685// 2 -- Fail at compile time
686// 3 -- Fail at runtime (DCHECK)
687// 4 -- [default] LOG(ERROR) at runtime
688// 5 -- LOG(ERROR) at runtime, only once per call-site
689
690#ifndef NOTIMPLEMENTED_POLICY
Vitaly Bukacbed2062015-08-17 12:54:05 -0700691// Select default policy: LOG(ERROR)
692#define NOTIMPLEMENTED_POLICY 4
693#endif
Vitaly Bukacbed2062015-08-17 12:54:05 -0700694
695#if defined(COMPILER_GCC)
696// On Linux, with GCC, we can use __PRETTY_FUNCTION__ to get the demangled name
697// of the current function in the NOTIMPLEMENTED message.
698#define NOTIMPLEMENTED_MSG "Not implemented reached in " << __PRETTY_FUNCTION__
699#else
700#define NOTIMPLEMENTED_MSG "NOT IMPLEMENTED"
701#endif
702
703#if NOTIMPLEMENTED_POLICY == 0
704#define NOTIMPLEMENTED() EAT_STREAM_PARAMETERS
705#elif NOTIMPLEMENTED_POLICY == 1
706// TODO, figure out how to generate a warning
Alex Vakulenko674f0eb2016-01-20 08:10:48 -0800707#define NOTIMPLEMENTED() static_assert(false, "NOT_IMPLEMENTED")
Vitaly Bukacbed2062015-08-17 12:54:05 -0700708#elif NOTIMPLEMENTED_POLICY == 2
Alex Vakulenko674f0eb2016-01-20 08:10:48 -0800709#define NOTIMPLEMENTED() static_assert(false, "NOT_IMPLEMENTED")
Vitaly Bukacbed2062015-08-17 12:54:05 -0700710#elif NOTIMPLEMENTED_POLICY == 3
711#define NOTIMPLEMENTED() NOTREACHED()
712#elif NOTIMPLEMENTED_POLICY == 4
713#define NOTIMPLEMENTED() LOG(ERROR) << NOTIMPLEMENTED_MSG
714#elif NOTIMPLEMENTED_POLICY == 5
715#define NOTIMPLEMENTED() do {\
716 static bool logged_once = false;\
717 LOG_IF(ERROR, !logged_once) << NOTIMPLEMENTED_MSG;\
718 logged_once = true;\
719} while(0);\
720EAT_STREAM_PARAMETERS
721#endif
722
723#endif // BASE_LOGGING_H_