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