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