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