• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
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 
146 namespace 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).
151 enum 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.
164 enum 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.
168 enum OldFileDeletionState { DELETE_OLD_LOG_FILE, APPEND_TO_OLD_LOG_FILE };
169 
170 enum 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)
177 typedef wchar_t PathChar;
178 #else
179 typedef 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".
195 BASE_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.
InitLogging(const PathChar * log_file,LoggingDestination logging_dest,LogLockingState lock_log,OldFileDeletionState delete_old,DcheckState dcheck_state)211 inline 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.
226 BASE_API void SetMinLogLevel(int level);
227 
228 // Gets the current log level.
229 BASE_API int GetMinLogLevel();
230 
231 // Gets the VLOG default verbosity level.
232 BASE_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.
238 BASE_API int GetVlogLevelHelper(const char* file_start, size_t N);
239 
240 template <size_t N>
GetVlogLevel(const char (& file)[N])241 int 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.
249 BASE_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.
255 BASE_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)
261 typedef void (*LogAssertHandlerFunction)(const std::string& str);
262 BASE_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.
268 typedef void (*LogReportHandlerFunction)(const std::string& str);
269 BASE_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.
275 typedef bool (*LogMessageHandlerFunction)(int severity,
276     const char* file, int line, size_t message_start, const std::string& str);
277 BASE_API void SetLogMessageHandler(LogMessageHandlerFunction handler);
278 BASE_API LogMessageHandlerFunction GetLogMessageHandler();
279 
280 typedef int LogSeverity;
281 const 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.
284 const LogSeverity LOG_INFO = 0;
285 const LogSeverity LOG_WARNING = 1;
286 const LogSeverity LOG_ERROR = 2;
287 const LogSeverity LOG_ERROR_REPORT = 3;
288 const LogSeverity LOG_FATAL = 4;
289 const LogSeverity LOG_NUM_SEVERITIES = 5;
290 
291 // LOG_DFATAL is LOG_FATAL in debug mode, ERROR in normal mode
292 #ifdef NDEBUG
293 const LogSeverity LOG_DFATAL = LOG_ERROR;
294 #else
295 const 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).
338 const 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.
462 template<class t1, class t2>
MakeCheckOpString(const t1 & v1,const t2 & v2,const char * names)463 std::string* MakeCheckOpString(const t1& v1, const t2& v2, const char* names) {
464   std::ostringstream ss;
465   ss << names << " (" << v1 << " vs. " << v2 << ")";
466   std::string* msg = new std::string(ss.str());
467   return msg;
468 }
469 
470 // MSVC doesn't like complex extern templates and DLLs.
471 #if !defined(COMPILER_MSVC)
472 // Commonly used instantiations of MakeCheckOpString<>. Explicitly instantiated
473 // in logging.cc.
474 extern template std::string* MakeCheckOpString<int, int>(
475     const int&, const int&, const char* names);
476 extern template std::string* MakeCheckOpString<unsigned long, unsigned long>(
477     const unsigned long&, const unsigned long&, const char* names);
478 extern template std::string* MakeCheckOpString<unsigned long, unsigned int>(
479     const unsigned long&, const unsigned int&, const char* names);
480 extern template std::string* MakeCheckOpString<unsigned int, unsigned long>(
481     const unsigned int&, const unsigned long&, const char* names);
482 extern template std::string* MakeCheckOpString<std::string, std::string>(
483     const std::string&, const std::string&, const char* name);
484 #endif
485 
486 // Helper macro for binary operators.
487 // Don't use this macro directly in your code, use CHECK_EQ et al below.
488 //
489 // TODO(akalin): Rewrite this so that constructs like if (...)
490 // CHECK_EQ(...) else { ... } work properly.
491 #define CHECK_OP(name, op, val1, val2)                          \
492   if (std::string* _result =                                    \
493       logging::Check##name##Impl((val1), (val2),                \
494                                  #val1 " " #op " " #val2))      \
495     logging::LogMessage(__FILE__, __LINE__, _result).stream()
496 
497 // Helper functions for CHECK_OP macro.
498 // The (int, int) specialization works around the issue that the compiler
499 // will not instantiate the template version of the function on values of
500 // unnamed enum type - see comment below.
501 #define DEFINE_CHECK_OP_IMPL(name, op) \
502   template <class t1, class t2> \
503   inline std::string* Check##name##Impl(const t1& v1, const t2& v2, \
504                                         const char* names) { \
505     if (v1 op v2) return NULL; \
506     else return MakeCheckOpString(v1, v2, names); \
507   } \
508   inline std::string* Check##name##Impl(int v1, int v2, const char* names) { \
509     if (v1 op v2) return NULL; \
510     else return MakeCheckOpString(v1, v2, names); \
511   }
512 DEFINE_CHECK_OP_IMPL(EQ, ==)
513 DEFINE_CHECK_OP_IMPL(NE, !=)
514 DEFINE_CHECK_OP_IMPL(LE, <=)
515 DEFINE_CHECK_OP_IMPL(LT, < )
516 DEFINE_CHECK_OP_IMPL(GE, >=)
517 DEFINE_CHECK_OP_IMPL(GT, > )
518 #undef DEFINE_CHECK_OP_IMPL
519 
520 #define CHECK_EQ(val1, val2) CHECK_OP(EQ, ==, val1, val2)
521 #define CHECK_NE(val1, val2) CHECK_OP(NE, !=, val1, val2)
522 #define CHECK_LE(val1, val2) CHECK_OP(LE, <=, val1, val2)
523 #define CHECK_LT(val1, val2) CHECK_OP(LT, < , val1, val2)
524 #define CHECK_GE(val1, val2) CHECK_OP(GE, >=, val1, val2)
525 #define CHECK_GT(val1, val2) CHECK_OP(GT, > , val1, val2)
526 
527 // http://crbug.com/16512 is open for a real fix for this.  For now, Windows
528 // uses OFFICIAL_BUILD and other platforms use the branding flag when NDEBUG is
529 // defined.
530 #if ( defined(OS_WIN) && defined(OFFICIAL_BUILD)) || \
531     (!defined(OS_WIN) && defined(NDEBUG) && defined(GOOGLE_CHROME_BUILD))
532 // Used by unit tests.
533 #define LOGGING_IS_OFFICIAL_BUILD
534 
535 // In order to have optimized code for official builds, remove DLOGs and
536 // DCHECKs.
537 #define ENABLE_DLOG 0
538 #define ENABLE_DCHECK 0
539 
540 #elif defined(NDEBUG)
541 // Otherwise, if we're a release build, remove DLOGs but not DCHECKs
542 // (since those can still be turned on via a command-line flag).
543 #define ENABLE_DLOG 0
544 #define ENABLE_DCHECK 1
545 
546 #else
547 // Otherwise, we're a debug build so enable DLOGs and DCHECKs.
548 #define ENABLE_DLOG 1
549 #define ENABLE_DCHECK 1
550 #endif
551 
552 // Definitions for DLOG et al.
553 
554 #if ENABLE_DLOG
555 
556 #define DLOG_IS_ON(severity) LOG_IS_ON(severity)
557 #define DLOG_IF(severity, condition) LOG_IF(severity, condition)
558 #define DLOG_ASSERT(condition) LOG_ASSERT(condition)
559 #define DPLOG_IF(severity, condition) PLOG_IF(severity, condition)
560 #define DVLOG_IF(verboselevel, condition) VLOG_IF(verboselevel, condition)
561 #define DVPLOG_IF(verboselevel, condition) VPLOG_IF(verboselevel, condition)
562 
563 #else  // ENABLE_DLOG
564 
565 // If ENABLE_DLOG is off, we want to avoid emitting any references to
566 // |condition| (which may reference a variable defined only if NDEBUG
567 // is not defined).  Contrast this with DCHECK et al., which has
568 // different behavior.
569 
570 #define DLOG_EAT_STREAM_PARAMETERS                                      \
571   true ? (void) 0 : ::logging::LogMessageVoidify() & LOG_STREAM(FATAL)
572 
573 #define DLOG_IS_ON(severity) false
574 #define DLOG_IF(severity, condition) DLOG_EAT_STREAM_PARAMETERS
575 #define DLOG_ASSERT(condition) DLOG_EAT_STREAM_PARAMETERS
576 #define DPLOG_IF(severity, condition) DLOG_EAT_STREAM_PARAMETERS
577 #define DVLOG_IF(verboselevel, condition) DLOG_EAT_STREAM_PARAMETERS
578 #define DVPLOG_IF(verboselevel, condition) DLOG_EAT_STREAM_PARAMETERS
579 
580 #endif  // ENABLE_DLOG
581 
582 // DEBUG_MODE is for uses like
583 //   if (DEBUG_MODE) foo.CheckThatFoo();
584 // instead of
585 //   #ifndef NDEBUG
586 //     foo.CheckThatFoo();
587 //   #endif
588 //
589 // We tie its state to ENABLE_DLOG.
590 enum { DEBUG_MODE = ENABLE_DLOG };
591 
592 #undef ENABLE_DLOG
593 
594 #define DLOG(severity)                                          \
595   LAZY_STREAM(LOG_STREAM(severity), DLOG_IS_ON(severity))
596 
597 #if defined(OS_WIN)
598 #define DLOG_GETLASTERROR(severity) \
599   LAZY_STREAM(LOG_GETLASTERROR_STREAM(severity), DLOG_IS_ON(severity))
600 #define DLOG_GETLASTERROR_MODULE(severity, module)                      \
601   LAZY_STREAM(LOG_GETLASTERROR_STREAM(severity, module),                \
602               DLOG_IS_ON(severity))
603 #elif defined(OS_POSIX)
604 #define DLOG_ERRNO(severity)                                    \
605   LAZY_STREAM(LOG_ERRNO_STREAM(severity), DLOG_IS_ON(severity))
606 #endif
607 
608 #define DPLOG(severity)                                         \
609   LAZY_STREAM(PLOG_STREAM(severity), DLOG_IS_ON(severity))
610 
611 #define DVLOG(verboselevel) DLOG_IF(INFO, VLOG_IS_ON(verboselevel))
612 
613 #define DVPLOG(verboselevel) DVPLOG_IF(verboselevel, VLOG_IS_ON(verboselevel))
614 
615 // Definitions for DCHECK et al.
616 
617 #if ENABLE_DCHECK
618 
619 #if defined(NDEBUG)
620 
621 #define COMPACT_GOOGLE_LOG_EX_DCHECK(ClassName, ...) \
622   COMPACT_GOOGLE_LOG_EX_ERROR_REPORT(ClassName , ##__VA_ARGS__)
623 #define COMPACT_GOOGLE_LOG_DCHECK COMPACT_GOOGLE_LOG_ERROR_REPORT
624 const LogSeverity LOG_DCHECK = LOG_ERROR_REPORT;
625 extern DcheckState g_dcheck_state;
626 #define DCHECK_IS_ON()                                                  \
627   ((::logging::g_dcheck_state ==                                        \
628     ::logging::ENABLE_DCHECK_FOR_NON_OFFICIAL_RELEASE_BUILDS) &&        \
629    LOG_IS_ON(DCHECK))
630 
631 #else  // defined(NDEBUG)
632 
633 // On a regular debug build, we want to have DCHECKs enabled.
634 #define COMPACT_GOOGLE_LOG_EX_DCHECK(ClassName, ...) \
635   COMPACT_GOOGLE_LOG_EX_FATAL(ClassName , ##__VA_ARGS__)
636 #define COMPACT_GOOGLE_LOG_DCHECK COMPACT_GOOGLE_LOG_FATAL
637 const LogSeverity LOG_DCHECK = LOG_FATAL;
638 #define DCHECK_IS_ON() true
639 
640 #endif  // defined(NDEBUG)
641 
642 #else  // ENABLE_DCHECK
643 
644 // These are just dummy values since DCHECK_IS_ON() is always false in
645 // this case.
646 #define COMPACT_GOOGLE_LOG_EX_DCHECK(ClassName, ...) \
647   COMPACT_GOOGLE_LOG_EX_INFO(ClassName , ##__VA_ARGS__)
648 #define COMPACT_GOOGLE_LOG_DCHECK COMPACT_GOOGLE_LOG_INFO
649 const LogSeverity LOG_DCHECK = LOG_INFO;
650 #define DCHECK_IS_ON() false
651 
652 #endif  // ENABLE_DCHECK
653 #undef ENABLE_DCHECK
654 
655 // DCHECK et al. make sure to reference |condition| regardless of
656 // whether DCHECKs are enabled; this is so that we don't get unused
657 // variable warnings if the only use of a variable is in a DCHECK.
658 // This behavior is different from DLOG_IF et al.
659 
660 #define DCHECK(condition)                                           \
661   LAZY_STREAM(LOG_STREAM(DCHECK), DCHECK_IS_ON() && !(condition))   \
662   << "Check failed: " #condition ". "
663 
664 #define DPCHECK(condition)                                          \
665   LAZY_STREAM(PLOG_STREAM(DCHECK), DCHECK_IS_ON() && !(condition))  \
666   << "Check failed: " #condition ". "
667 
668 // Helper macro for binary operators.
669 // Don't use this macro directly in your code, use DCHECK_EQ et al below.
670 #define DCHECK_OP(name, op, val1, val2)                         \
671   if (DCHECK_IS_ON())                                           \
672     if (std::string* _result =                                  \
673         logging::Check##name##Impl((val1), (val2),              \
674                                    #val1 " " #op " " #val2))    \
675       logging::LogMessage(                                      \
676           __FILE__, __LINE__, ::logging::LOG_DCHECK,            \
677           _result).stream()
678 
679 // Equality/Inequality checks - compare two values, and log a
680 // LOG_DCHECK message including the two values when the result is not
681 // as expected.  The values must have operator<<(ostream, ...)
682 // defined.
683 //
684 // You may append to the error message like so:
685 //   DCHECK_NE(1, 2) << ": The world must be ending!";
686 //
687 // We are very careful to ensure that each argument is evaluated exactly
688 // once, and that anything which is legal to pass as a function argument is
689 // legal here.  In particular, the arguments may be temporary expressions
690 // which will end up being destroyed at the end of the apparent statement,
691 // for example:
692 //   DCHECK_EQ(string("abc")[1], 'b');
693 //
694 // WARNING: These may not compile correctly if one of the arguments is a pointer
695 // and the other is NULL. To work around this, simply static_cast NULL to the
696 // type of the desired pointer.
697 
698 #define DCHECK_EQ(val1, val2) DCHECK_OP(EQ, ==, val1, val2)
699 #define DCHECK_NE(val1, val2) DCHECK_OP(NE, !=, val1, val2)
700 #define DCHECK_LE(val1, val2) DCHECK_OP(LE, <=, val1, val2)
701 #define DCHECK_LT(val1, val2) DCHECK_OP(LT, < , val1, val2)
702 #define DCHECK_GE(val1, val2) DCHECK_OP(GE, >=, val1, val2)
703 #define DCHECK_GT(val1, val2) DCHECK_OP(GT, > , val1, val2)
704 
705 #define NOTREACHED() DCHECK(false)
706 
707 // Redefine the standard assert to use our nice log files
708 #undef assert
709 #define assert(x) DLOG_ASSERT(x)
710 
711 // This class more or less represents a particular log message.  You
712 // create an instance of LogMessage and then stream stuff to it.
713 // When you finish streaming to it, ~LogMessage is called and the
714 // full message gets streamed to the appropriate destination.
715 //
716 // You shouldn't actually use LogMessage's constructor to log things,
717 // though.  You should use the LOG() macro (and variants thereof)
718 // above.
719 class BASE_API LogMessage {
720  public:
721   LogMessage(const char* file, int line, LogSeverity severity, int ctr);
722 
723   // Two special constructors that generate reduced amounts of code at
724   // LOG call sites for common cases.
725   //
726   // Used for LOG(INFO): Implied are:
727   // severity = LOG_INFO, ctr = 0
728   //
729   // Using this constructor instead of the more complex constructor above
730   // saves a couple of bytes per call site.
731   LogMessage(const char* file, int line);
732 
733   // Used for LOG(severity) where severity != INFO.  Implied
734   // are: ctr = 0
735   //
736   // Using this constructor instead of the more complex constructor above
737   // saves a couple of bytes per call site.
738   LogMessage(const char* file, int line, LogSeverity severity);
739 
740   // A special constructor used for check failures.  Takes ownership
741   // of the given string.
742   // Implied severity = LOG_FATAL
743   LogMessage(const char* file, int line, std::string* result);
744 
745   // A special constructor used for check failures, with the option to
746   // specify severity.  Takes ownership of the given string.
747   LogMessage(const char* file, int line, LogSeverity severity,
748              std::string* result);
749 
750   ~LogMessage();
751 
stream()752   std::ostream& stream() { return stream_; }
753 
754  private:
755   void Init(const char* file, int line);
756 
757   LogSeverity severity_;
758   std::ostringstream stream_;
759   size_t message_start_;  // Offset of the start of the message (past prefix
760                           // info).
761   // The file and line information passed in to the constructor.
762   const char* file_;
763   const int line_;
764 
765 #if defined(OS_WIN)
766   // Stores the current value of GetLastError in the constructor and restores
767   // it in the destructor by calling SetLastError.
768   // This is useful since the LogMessage class uses a lot of Win32 calls
769   // that will lose the value of GLE and the code that called the log function
770   // will have lost the thread error value when the log call returns.
771   class SaveLastError {
772    public:
773     SaveLastError();
774     ~SaveLastError();
775 
get_error()776     unsigned long get_error() const { return last_error_; }
777 
778    protected:
779     unsigned long last_error_;
780   };
781 
782   SaveLastError last_error_;
783 #endif
784 
785   DISALLOW_COPY_AND_ASSIGN(LogMessage);
786 };
787 
788 // A non-macro interface to the log facility; (useful
789 // when the logging level is not a compile-time constant).
LogAtLevel(int const log_level,std::string const & msg)790 inline void LogAtLevel(int const log_level, std::string const &msg) {
791   LogMessage(__FILE__, __LINE__, log_level).stream() << msg;
792 }
793 
794 // This class is used to explicitly ignore values in the conditional
795 // logging macros.  This avoids compiler warnings like "value computed
796 // is not used" and "statement has no effect".
797 class BASE_API LogMessageVoidify {
798  public:
LogMessageVoidify()799   LogMessageVoidify() { }
800   // This has to be an operator with a precedence lower than << but
801   // higher than ?:
802   void operator&(std::ostream&) { }
803 };
804 
805 #if defined(OS_WIN)
806 typedef unsigned long SystemErrorCode;
807 #elif defined(OS_POSIX)
808 typedef int SystemErrorCode;
809 #endif
810 
811 // Alias for ::GetLastError() on Windows and errno on POSIX. Avoids having to
812 // pull in windows.h just for GetLastError() and DWORD.
813 BASE_API SystemErrorCode GetLastSystemErrorCode();
814 
815 #if defined(OS_WIN)
816 // Appends a formatted system message of the GetLastError() type.
817 class BASE_API Win32ErrorLogMessage {
818  public:
819   Win32ErrorLogMessage(const char* file,
820                        int line,
821                        LogSeverity severity,
822                        SystemErrorCode err,
823                        const char* module);
824 
825   Win32ErrorLogMessage(const char* file,
826                        int line,
827                        LogSeverity severity,
828                        SystemErrorCode err);
829 
830   // Appends the error message before destructing the encapsulated class.
831   ~Win32ErrorLogMessage();
832 
stream()833   std::ostream& stream() { return log_message_.stream(); }
834 
835  private:
836   SystemErrorCode err_;
837   // Optional name of the module defining the error.
838   const char* module_;
839   LogMessage log_message_;
840 
841   DISALLOW_COPY_AND_ASSIGN(Win32ErrorLogMessage);
842 };
843 #elif defined(OS_POSIX)
844 // Appends a formatted system message of the errno type
845 class ErrnoLogMessage {
846  public:
847   ErrnoLogMessage(const char* file,
848                   int line,
849                   LogSeverity severity,
850                   SystemErrorCode err);
851 
852   // Appends the error message before destructing the encapsulated class.
853   ~ErrnoLogMessage();
854 
stream()855   std::ostream& stream() { return log_message_.stream(); }
856 
857  private:
858   SystemErrorCode err_;
859   LogMessage log_message_;
860 
861   DISALLOW_COPY_AND_ASSIGN(ErrnoLogMessage);
862 };
863 #endif  // OS_WIN
864 
865 // Closes the log file explicitly if open.
866 // NOTE: Since the log file is opened as necessary by the action of logging
867 //       statements, there's no guarantee that it will stay closed
868 //       after this call.
869 BASE_API void CloseLogFile();
870 
871 // Async signal safe logging mechanism.
872 BASE_API void RawLog(int level, const char* message);
873 
874 #define RAW_LOG(level, message) logging::RawLog(logging::LOG_ ## level, message)
875 
876 #define RAW_CHECK(condition)                                                   \
877   do {                                                                         \
878     if (!(condition))                                                          \
879       logging::RawLog(logging::LOG_FATAL, "Check failed: " #condition "\n");   \
880   } while (0)
881 
882 }  // namespace logging
883 
884 // These functions are provided as a convenience for logging, which is where we
885 // use streams (it is against Google style to use streams in other places). It
886 // is designed to allow you to emit non-ASCII Unicode strings to the log file,
887 // which is normally ASCII. It is relatively slow, so try not to use it for
888 // common cases. Non-ASCII characters will be converted to UTF-8 by these
889 // operators.
890 BASE_API std::ostream& operator<<(std::ostream& out, const wchar_t* wstr);
891 inline std::ostream& operator<<(std::ostream& out, const std::wstring& wstr) {
892   return out << wstr.c_str();
893 }
894 
895 // The NOTIMPLEMENTED() macro annotates codepaths which have
896 // not been implemented yet.
897 //
898 // The implementation of this macro is controlled by NOTIMPLEMENTED_POLICY:
899 //   0 -- Do nothing (stripped by compiler)
900 //   1 -- Warn at compile time
901 //   2 -- Fail at compile time
902 //   3 -- Fail at runtime (DCHECK)
903 //   4 -- [default] LOG(ERROR) at runtime
904 //   5 -- LOG(ERROR) at runtime, only once per call-site
905 
906 #ifndef NOTIMPLEMENTED_POLICY
907 // Select default policy: LOG(ERROR)
908 #define NOTIMPLEMENTED_POLICY 4
909 #endif
910 
911 #if defined(COMPILER_GCC)
912 // On Linux, with GCC, we can use __PRETTY_FUNCTION__ to get the demangled name
913 // of the current function in the NOTIMPLEMENTED message.
914 #define NOTIMPLEMENTED_MSG "Not implemented reached in " << __PRETTY_FUNCTION__
915 #else
916 #define NOTIMPLEMENTED_MSG "NOT IMPLEMENTED"
917 #endif
918 
919 #if NOTIMPLEMENTED_POLICY == 0
920 #define NOTIMPLEMENTED() ;
921 #elif NOTIMPLEMENTED_POLICY == 1
922 // TODO, figure out how to generate a warning
923 #define NOTIMPLEMENTED() COMPILE_ASSERT(false, NOT_IMPLEMENTED)
924 #elif NOTIMPLEMENTED_POLICY == 2
925 #define NOTIMPLEMENTED() COMPILE_ASSERT(false, NOT_IMPLEMENTED)
926 #elif NOTIMPLEMENTED_POLICY == 3
927 #define NOTIMPLEMENTED() NOTREACHED()
928 #elif NOTIMPLEMENTED_POLICY == 4
929 #define NOTIMPLEMENTED() LOG(ERROR) << NOTIMPLEMENTED_MSG
930 #elif NOTIMPLEMENTED_POLICY == 5
931 #define NOTIMPLEMENTED() do {\
932   static int count = 0;\
933   LOG_IF(ERROR, 0 == count++) << NOTIMPLEMENTED_MSG;\
934 } while(0)
935 #endif
936 
937 namespace base {
938 
939 class StringPiece;
940 
941 // Allows StringPiece to be logged.
942 BASE_API std::ostream& operator<<(std::ostream& o, const StringPiece& piece);
943 
944 }  // namespace base
945 
946 #endif  // BASE_LOGGING_H_
947