Add missing pnacl libraries and headers and tools.
[chromium-blink-merge.git] / base / logging.h
blob55c9ebfafbf3db7f44419145bcb486073fff6e88
1 // Copyright (c) 2012 The Chromium Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
5 #ifndef BASE_LOGGING_H_
6 #define BASE_LOGGING_H_
8 #include <cassert>
9 #include <string>
10 #include <cstring>
11 #include <sstream>
13 #include "base/base_export.h"
14 #include "base/basictypes.h"
15 #include "base/debug/debugger.h"
16 #include "build/build_config.h"
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.
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.
36 // The code for DebugMessage.exe is only one line. In WinMain, do:
37 // MessageBox(NULL, GetCommandLineW(), L"Fatal Error", 0);
39 // If DebugMessage.exe is not found, the logging code will use a normal
40 // MessageBox, potentially causing the problems discussed above.
43 // Instructions
44 // ------------
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.,
49 // LOG(INFO) << "Found " << num_cookies << " cookies";
51 // You can also do conditional logging:
53 // LOG_IF(INFO, num_cookies > 10) << "Got lots of cookies";
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.
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.
63 // There are also "debug mode" logging macros like the ones above:
65 // DLOG(INFO) << "Found cookies";
67 // DLOG_IF(INFO, num_cookies > 10) << "Got lots of cookies";
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.
73 // We also have
75 // LOG_ASSERT(assertion);
76 // DLOG_ASSERT(assertion);
78 // which is syntactic sugar for {,D}LOG_IF(FATAL, assert fails) << assertion;
80 // There are "verbose level" logging macros. They look like
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";
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
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.
104 // There's also VLOG_IS_ON(n) "verbose level" condition macro. To be used as
106 // if (VLOG_IS_ON(2)) {
107 // // do some logging preparation and logging
108 // // that can't be accomplished with just VLOG(2) << ...;
109 // }
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.
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";
119 // We also override the standard 'assert' to use 'DLOG_ASSERT'.
121 // Lastly, there is:
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";
130 // which append the last system error to the message in string form (taken from
131 // GetLastError() on Windows and errno on POSIX).
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.
137 // Very important: logging a message at the FATAL severity level causes
138 // the program to terminate (after the message is logged).
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.
144 // There is also the special severity of DFATAL, which logs FATAL in
145 // debug mode, ERROR in normal mode.
147 namespace logging {
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 };
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.
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 };
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 };
171 enum DcheckState {
172 DISABLE_DCHECK_FOR_NON_OFFICIAL_RELEASE_BUILDS,
173 ENABLE_DCHECK_FOR_NON_OFFICIAL_RELEASE_BUILDS
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
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
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);
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.
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.
213 // This function may be called a second time to re-direct logging (e.g after
214 // loging in to a user partition), however it should never be called more than
215 // twice.
216 inline bool InitLogging(const PathChar* log_file,
217 LoggingDestination logging_dest,
218 LogLockingState lock_log,
219 OldFileDeletionState delete_old,
220 DcheckState dcheck_state) {
221 return BaseInitLoggingImpl(log_file, logging_dest, lock_log,
222 delete_old, dcheck_state);
225 // Sets the log level. Anything at or above this level will be written to the
226 // log file/displayed to the user (if applicable). Anything below this level
227 // will be silently ignored. The log level defaults to 0 (everything is logged
228 // up to level INFO) if this function is not called.
229 // Note that log messages for VLOG(x) are logged at level -x, so setting
230 // the min log level to negative values enables verbose logging.
231 BASE_EXPORT void SetMinLogLevel(int level);
233 // Gets the current log level.
234 BASE_EXPORT int GetMinLogLevel();
236 // Gets the VLOG default verbosity level.
237 BASE_EXPORT int GetVlogVerbosity();
239 // Gets the current vlog level for the given file (usually taken from
240 // __FILE__).
242 // Note that |N| is the size *with* the null terminator.
243 BASE_EXPORT int GetVlogLevelHelper(const char* file_start, size_t N);
245 template <size_t N>
246 int GetVlogLevel(const char (&file)[N]) {
247 return GetVlogLevelHelper(file, N);
250 // Sets the common items you want to be prepended to each log message.
251 // process and thread IDs default to off, the timestamp defaults to on.
252 // If this function is not called, logging defaults to writing the timestamp
253 // only.
254 BASE_EXPORT void SetLogItems(bool enable_process_id, bool enable_thread_id,
255 bool enable_timestamp, bool enable_tickcount);
257 // Sets whether or not you'd like to see fatal debug messages popped up in
258 // a dialog box or not.
259 // Dialogs are not shown by default.
260 BASE_EXPORT void SetShowErrorDialogs(bool enable_dialogs);
262 // Sets the Log Assert Handler that will be used to notify of check failures.
263 // The default handler shows a dialog box and then terminate the process,
264 // however clients can use this function to override with their own handling
265 // (e.g. a silent one for Unit Tests)
266 typedef void (*LogAssertHandlerFunction)(const std::string& str);
267 BASE_EXPORT void SetLogAssertHandler(LogAssertHandlerFunction handler);
269 // Sets the Log Report Handler that will be used to notify of check failures
270 // in non-debug mode. The default handler shows a dialog box and continues
271 // the execution, however clients can use this function to override with their
272 // own handling.
273 typedef void (*LogReportHandlerFunction)(const std::string& str);
274 BASE_EXPORT void SetLogReportHandler(LogReportHandlerFunction handler);
276 // Sets the Log Message Handler that gets passed every log message before
277 // it's sent to other log destinations (if any).
278 // Returns true to signal that it handled the message and the message
279 // should not be sent to other log destinations.
280 typedef bool (*LogMessageHandlerFunction)(int severity,
281 const char* file, int line, size_t message_start, const std::string& str);
282 BASE_EXPORT void SetLogMessageHandler(LogMessageHandlerFunction handler);
283 BASE_EXPORT LogMessageHandlerFunction GetLogMessageHandler();
285 typedef int LogSeverity;
286 const LogSeverity LOG_VERBOSE = -1; // This is level 1 verbosity
287 // Note: the log severities are used to index into the array of names,
288 // see log_severity_names.
289 const LogSeverity LOG_INFO = 0;
290 const LogSeverity LOG_WARNING = 1;
291 const LogSeverity LOG_ERROR = 2;
292 const LogSeverity LOG_ERROR_REPORT = 3;
293 const LogSeverity LOG_FATAL = 4;
294 const LogSeverity LOG_NUM_SEVERITIES = 5;
296 // LOG_DFATAL is LOG_FATAL in debug mode, ERROR in normal mode
297 #ifdef NDEBUG
298 const LogSeverity LOG_DFATAL = LOG_ERROR;
299 #else
300 const LogSeverity LOG_DFATAL = LOG_FATAL;
301 #endif
303 // A few definitions of macros that don't generate much code. These are used
304 // by LOG() and LOG_IF, etc. Since these are used all over our code, it's
305 // better to have compact code for these operations.
306 #define COMPACT_GOOGLE_LOG_EX_INFO(ClassName, ...) \
307 logging::ClassName(__FILE__, __LINE__, logging::LOG_INFO , ##__VA_ARGS__)
308 #define COMPACT_GOOGLE_LOG_EX_WARNING(ClassName, ...) \
309 logging::ClassName(__FILE__, __LINE__, logging::LOG_WARNING , ##__VA_ARGS__)
310 #define COMPACT_GOOGLE_LOG_EX_ERROR(ClassName, ...) \
311 logging::ClassName(__FILE__, __LINE__, logging::LOG_ERROR , ##__VA_ARGS__)
312 #define COMPACT_GOOGLE_LOG_EX_ERROR_REPORT(ClassName, ...) \
313 logging::ClassName(__FILE__, __LINE__, \
314 logging::LOG_ERROR_REPORT , ##__VA_ARGS__)
315 #define COMPACT_GOOGLE_LOG_EX_FATAL(ClassName, ...) \
316 logging::ClassName(__FILE__, __LINE__, logging::LOG_FATAL , ##__VA_ARGS__)
317 #define COMPACT_GOOGLE_LOG_EX_DFATAL(ClassName, ...) \
318 logging::ClassName(__FILE__, __LINE__, logging::LOG_DFATAL , ##__VA_ARGS__)
320 #define COMPACT_GOOGLE_LOG_INFO \
321 COMPACT_GOOGLE_LOG_EX_INFO(LogMessage)
322 #define COMPACT_GOOGLE_LOG_WARNING \
323 COMPACT_GOOGLE_LOG_EX_WARNING(LogMessage)
324 #define COMPACT_GOOGLE_LOG_ERROR \
325 COMPACT_GOOGLE_LOG_EX_ERROR(LogMessage)
326 #define COMPACT_GOOGLE_LOG_ERROR_REPORT \
327 COMPACT_GOOGLE_LOG_EX_ERROR_REPORT(LogMessage)
328 #define COMPACT_GOOGLE_LOG_FATAL \
329 COMPACT_GOOGLE_LOG_EX_FATAL(LogMessage)
330 #define COMPACT_GOOGLE_LOG_DFATAL \
331 COMPACT_GOOGLE_LOG_EX_DFATAL(LogMessage)
333 #if defined(OS_WIN)
334 // wingdi.h defines ERROR to be 0. When we call LOG(ERROR), it gets
335 // substituted with 0, and it expands to COMPACT_GOOGLE_LOG_0. To allow us
336 // to keep using this syntax, we define this macro to do the same thing
337 // as COMPACT_GOOGLE_LOG_ERROR, and also define ERROR the same way that
338 // the Windows SDK does for consistency.
339 #define ERROR 0
340 #define COMPACT_GOOGLE_LOG_EX_0(ClassName, ...) \
341 COMPACT_GOOGLE_LOG_EX_ERROR(ClassName , ##__VA_ARGS__)
342 #define COMPACT_GOOGLE_LOG_0 COMPACT_GOOGLE_LOG_ERROR
343 // Needed for LOG_IS_ON(ERROR).
344 const LogSeverity LOG_0 = LOG_ERROR;
345 #endif
347 // As special cases, we can assume that LOG_IS_ON(ERROR_REPORT) and
348 // LOG_IS_ON(FATAL) always hold. Also, LOG_IS_ON(DFATAL) always holds
349 // in debug mode. In particular, CHECK()s will always fire if they
350 // fail.
351 #define LOG_IS_ON(severity) \
352 ((::logging::LOG_ ## severity) >= ::logging::GetMinLogLevel())
354 // We can't do any caching tricks with VLOG_IS_ON() like the
355 // google-glog version since it requires GCC extensions. This means
356 // that using the v-logging functions in conjunction with --vmodule
357 // may be slow.
358 #define VLOG_IS_ON(verboselevel) \
359 ((verboselevel) <= ::logging::GetVlogLevel(__FILE__))
361 // Helper macro which avoids evaluating the arguments to a stream if
362 // the condition doesn't hold.
363 #define LAZY_STREAM(stream, condition) \
364 !(condition) ? (void) 0 : ::logging::LogMessageVoidify() & (stream)
366 // We use the preprocessor's merging operator, "##", so that, e.g.,
367 // LOG(INFO) becomes the token COMPACT_GOOGLE_LOG_INFO. There's some funny
368 // subtle difference between ostream member streaming functions (e.g.,
369 // ostream::operator<<(int) and ostream non-member streaming functions
370 // (e.g., ::operator<<(ostream&, string&): it turns out that it's
371 // impossible to stream something like a string directly to an unnamed
372 // ostream. We employ a neat hack by calling the stream() member
373 // function of LogMessage which seems to avoid the problem.
374 #define LOG_STREAM(severity) COMPACT_GOOGLE_LOG_ ## severity.stream()
376 #define LOG(severity) LAZY_STREAM(LOG_STREAM(severity), LOG_IS_ON(severity))
377 #define LOG_IF(severity, condition) \
378 LAZY_STREAM(LOG_STREAM(severity), LOG_IS_ON(severity) && (condition))
380 #define SYSLOG(severity) LOG(severity)
381 #define SYSLOG_IF(severity, condition) LOG_IF(severity, condition)
383 // The VLOG macros log with negative verbosities.
384 #define VLOG_STREAM(verbose_level) \
385 logging::LogMessage(__FILE__, __LINE__, -verbose_level).stream()
387 #define VLOG(verbose_level) \
388 LAZY_STREAM(VLOG_STREAM(verbose_level), VLOG_IS_ON(verbose_level))
390 #define VLOG_IF(verbose_level, condition) \
391 LAZY_STREAM(VLOG_STREAM(verbose_level), \
392 VLOG_IS_ON(verbose_level) && (condition))
394 #if defined (OS_WIN)
395 #define VPLOG_STREAM(verbose_level) \
396 logging::Win32ErrorLogMessage(__FILE__, __LINE__, -verbose_level, \
397 ::logging::GetLastSystemErrorCode()).stream()
398 #elif defined(OS_POSIX)
399 #define VPLOG_STREAM(verbose_level) \
400 logging::ErrnoLogMessage(__FILE__, __LINE__, -verbose_level, \
401 ::logging::GetLastSystemErrorCode()).stream()
402 #endif
404 #define VPLOG(verbose_level) \
405 LAZY_STREAM(VPLOG_STREAM(verbose_level), VLOG_IS_ON(verbose_level))
407 #define VPLOG_IF(verbose_level, condition) \
408 LAZY_STREAM(VPLOG_STREAM(verbose_level), \
409 VLOG_IS_ON(verbose_level) && (condition))
411 // TODO(akalin): Add more VLOG variants, e.g. VPLOG.
413 #define LOG_ASSERT(condition) \
414 LOG_IF(FATAL, !(condition)) << "Assert failed: " #condition ". "
415 #define SYSLOG_ASSERT(condition) \
416 SYSLOG_IF(FATAL, !(condition)) << "Assert failed: " #condition ". "
418 #if defined(OS_WIN)
419 #define LOG_GETLASTERROR_STREAM(severity) \
420 COMPACT_GOOGLE_LOG_EX_ ## severity(Win32ErrorLogMessage, \
421 ::logging::GetLastSystemErrorCode()).stream()
422 #define LOG_GETLASTERROR(severity) \
423 LAZY_STREAM(LOG_GETLASTERROR_STREAM(severity), LOG_IS_ON(severity))
424 #define LOG_GETLASTERROR_MODULE_STREAM(severity, module) \
425 COMPACT_GOOGLE_LOG_EX_ ## severity(Win32ErrorLogMessage, \
426 ::logging::GetLastSystemErrorCode(), module).stream()
427 #define LOG_GETLASTERROR_MODULE(severity, module) \
428 LAZY_STREAM(LOG_GETLASTERROR_STREAM(severity, module), \
429 LOG_IS_ON(severity))
430 // PLOG_STREAM is used by PLOG, which is the usual error logging macro
431 // for each platform.
432 #define PLOG_STREAM(severity) LOG_GETLASTERROR_STREAM(severity)
433 #elif defined(OS_POSIX)
434 #define LOG_ERRNO_STREAM(severity) \
435 COMPACT_GOOGLE_LOG_EX_ ## severity(ErrnoLogMessage, \
436 ::logging::GetLastSystemErrorCode()).stream()
437 #define LOG_ERRNO(severity) \
438 LAZY_STREAM(LOG_ERRNO_STREAM(severity), LOG_IS_ON(severity))
439 // PLOG_STREAM is used by PLOG, which is the usual error logging macro
440 // for each platform.
441 #define PLOG_STREAM(severity) LOG_ERRNO_STREAM(severity)
442 #endif
444 #define PLOG(severity) \
445 LAZY_STREAM(PLOG_STREAM(severity), LOG_IS_ON(severity))
447 #define PLOG_IF(severity, condition) \
448 LAZY_STREAM(PLOG_STREAM(severity), LOG_IS_ON(severity) && (condition))
450 #if defined(OFFICIAL_BUILD) && defined(NDEBUG)
451 #define LOGGING_IS_OFFICIAL_BUILD 1
452 #else
453 #define LOGGING_IS_OFFICIAL_BUILD 0
454 #endif
456 // The actual stream used isn't important.
457 #define EAT_STREAM_PARAMETERS \
458 true ? (void) 0 : ::logging::LogMessageVoidify() & LOG_STREAM(FATAL)
460 // CHECK dies with a fatal error if condition is not true. It is *not*
461 // controlled by NDEBUG, so the check will be executed regardless of
462 // compilation mode.
464 // We make sure CHECK et al. always evaluates their arguments, as
465 // doing CHECK(FunctionWithSideEffect()) is a common idiom.
467 #if LOGGING_IS_OFFICIAL_BUILD
469 // Make all CHECK functions discard their log strings to reduce code
470 // bloat for official builds.
472 // TODO(akalin): This would be more valuable if there were some way to
473 // remove BreakDebugger() from the backtrace, perhaps by turning it
474 // into a macro (like __debugbreak() on Windows).
475 #define CHECK(condition) \
476 !(condition) ? ::base::debug::BreakDebugger() : EAT_STREAM_PARAMETERS
478 #define PCHECK(condition) CHECK(condition)
480 #define CHECK_OP(name, op, val1, val2) CHECK((val1) op (val2))
482 #else
484 #define CHECK(condition) \
485 LAZY_STREAM(LOG_STREAM(FATAL), !(condition)) \
486 << "Check failed: " #condition ". "
488 #define PCHECK(condition) \
489 LAZY_STREAM(PLOG_STREAM(FATAL), !(condition)) \
490 << "Check failed: " #condition ". "
492 // Helper macro for binary operators.
493 // Don't use this macro directly in your code, use CHECK_EQ et al below.
495 // TODO(akalin): Rewrite this so that constructs like if (...)
496 // CHECK_EQ(...) else { ... } work properly.
497 #define CHECK_OP(name, op, val1, val2) \
498 if (std::string* _result = \
499 logging::Check##name##Impl((val1), (val2), \
500 #val1 " " #op " " #val2)) \
501 logging::LogMessage(__FILE__, __LINE__, _result).stream()
503 #endif
505 // Build the error message string. This is separate from the "Impl"
506 // function template because it is not performance critical and so can
507 // be out of line, while the "Impl" code should be inline. Caller
508 // takes ownership of the returned string.
509 template<class t1, class t2>
510 std::string* MakeCheckOpString(const t1& v1, const t2& v2, const char* names) {
511 std::ostringstream ss;
512 ss << names << " (" << v1 << " vs. " << v2 << ")";
513 std::string* msg = new std::string(ss.str());
514 return msg;
517 // MSVC doesn't like complex extern templates and DLLs.
518 #if !defined(COMPILER_MSVC)
519 // Commonly used instantiations of MakeCheckOpString<>. Explicitly instantiated
520 // in logging.cc.
521 extern template BASE_EXPORT std::string* MakeCheckOpString<int, int>(
522 const int&, const int&, const char* names);
523 extern template BASE_EXPORT
524 std::string* MakeCheckOpString<unsigned long, unsigned long>(
525 const unsigned long&, const unsigned long&, const char* names);
526 extern template BASE_EXPORT
527 std::string* MakeCheckOpString<unsigned long, unsigned int>(
528 const unsigned long&, const unsigned int&, const char* names);
529 extern template BASE_EXPORT
530 std::string* MakeCheckOpString<unsigned int, unsigned long>(
531 const unsigned int&, const unsigned long&, const char* names);
532 extern template BASE_EXPORT
533 std::string* MakeCheckOpString<std::string, std::string>(
534 const std::string&, const std::string&, const char* name);
535 #endif
537 // Helper functions for CHECK_OP macro.
538 // The (int, int) specialization works around the issue that the compiler
539 // will not instantiate the template version of the function on values of
540 // unnamed enum type - see comment below.
541 #define DEFINE_CHECK_OP_IMPL(name, op) \
542 template <class t1, class t2> \
543 inline std::string* Check##name##Impl(const t1& v1, const t2& v2, \
544 const char* names) { \
545 if (v1 op v2) return NULL; \
546 else return MakeCheckOpString(v1, v2, names); \
548 inline std::string* Check##name##Impl(int v1, int v2, const char* names) { \
549 if (v1 op v2) return NULL; \
550 else return MakeCheckOpString(v1, v2, names); \
552 DEFINE_CHECK_OP_IMPL(EQ, ==)
553 DEFINE_CHECK_OP_IMPL(NE, !=)
554 DEFINE_CHECK_OP_IMPL(LE, <=)
555 DEFINE_CHECK_OP_IMPL(LT, < )
556 DEFINE_CHECK_OP_IMPL(GE, >=)
557 DEFINE_CHECK_OP_IMPL(GT, > )
558 #undef DEFINE_CHECK_OP_IMPL
560 #define CHECK_EQ(val1, val2) CHECK_OP(EQ, ==, val1, val2)
561 #define CHECK_NE(val1, val2) CHECK_OP(NE, !=, val1, val2)
562 #define CHECK_LE(val1, val2) CHECK_OP(LE, <=, val1, val2)
563 #define CHECK_LT(val1, val2) CHECK_OP(LT, < , val1, val2)
564 #define CHECK_GE(val1, val2) CHECK_OP(GE, >=, val1, val2)
565 #define CHECK_GT(val1, val2) CHECK_OP(GT, > , val1, val2)
567 #if LOGGING_IS_OFFICIAL_BUILD
568 // In order to have optimized code for official builds, remove DLOGs and
569 // DCHECKs.
570 #define ENABLE_DLOG 0
571 #define ENABLE_DCHECK 0
573 #elif defined(NDEBUG)
574 // Otherwise, if we're a release build, remove DLOGs but not DCHECKs
575 // (since those can still be turned on via a command-line flag).
576 #define ENABLE_DLOG 0
577 #define ENABLE_DCHECK 1
579 #else
580 // Otherwise, we're a debug build so enable DLOGs and DCHECKs.
581 #define ENABLE_DLOG 1
582 #define ENABLE_DCHECK 1
583 #endif
585 // Definitions for DLOG et al.
587 #if ENABLE_DLOG
589 #define DLOG_IS_ON(severity) LOG_IS_ON(severity)
590 #define DLOG_IF(severity, condition) LOG_IF(severity, condition)
591 #define DLOG_ASSERT(condition) LOG_ASSERT(condition)
592 #define DPLOG_IF(severity, condition) PLOG_IF(severity, condition)
593 #define DVLOG_IF(verboselevel, condition) VLOG_IF(verboselevel, condition)
594 #define DVPLOG_IF(verboselevel, condition) VPLOG_IF(verboselevel, condition)
596 #else // ENABLE_DLOG
598 // If ENABLE_DLOG is off, we want to avoid emitting any references to
599 // |condition| (which may reference a variable defined only if NDEBUG
600 // is not defined). Contrast this with DCHECK et al., which has
601 // different behavior.
603 #define DLOG_IS_ON(severity) false
604 #define DLOG_IF(severity, condition) EAT_STREAM_PARAMETERS
605 #define DLOG_ASSERT(condition) EAT_STREAM_PARAMETERS
606 #define DPLOG_IF(severity, condition) EAT_STREAM_PARAMETERS
607 #define DVLOG_IF(verboselevel, condition) EAT_STREAM_PARAMETERS
608 #define DVPLOG_IF(verboselevel, condition) EAT_STREAM_PARAMETERS
610 #endif // ENABLE_DLOG
612 // DEBUG_MODE is for uses like
613 // if (DEBUG_MODE) foo.CheckThatFoo();
614 // instead of
615 // #ifndef NDEBUG
616 // foo.CheckThatFoo();
617 // #endif
619 // We tie its state to ENABLE_DLOG.
620 enum { DEBUG_MODE = ENABLE_DLOG };
622 #undef ENABLE_DLOG
624 #define DLOG(severity) \
625 LAZY_STREAM(LOG_STREAM(severity), DLOG_IS_ON(severity))
627 #if defined(OS_WIN)
628 #define DLOG_GETLASTERROR(severity) \
629 LAZY_STREAM(LOG_GETLASTERROR_STREAM(severity), DLOG_IS_ON(severity))
630 #define DLOG_GETLASTERROR_MODULE(severity, module) \
631 LAZY_STREAM(LOG_GETLASTERROR_STREAM(severity, module), \
632 DLOG_IS_ON(severity))
633 #elif defined(OS_POSIX)
634 #define DLOG_ERRNO(severity) \
635 LAZY_STREAM(LOG_ERRNO_STREAM(severity), DLOG_IS_ON(severity))
636 #endif
638 #define DPLOG(severity) \
639 LAZY_STREAM(PLOG_STREAM(severity), DLOG_IS_ON(severity))
641 #define DVLOG(verboselevel) DVLOG_IF(verboselevel, VLOG_IS_ON(verboselevel))
643 #define DVPLOG(verboselevel) DVPLOG_IF(verboselevel, VLOG_IS_ON(verboselevel))
645 // Definitions for DCHECK et al.
647 #if ENABLE_DCHECK
649 #if defined(NDEBUG)
651 BASE_EXPORT DcheckState get_dcheck_state();
652 BASE_EXPORT void set_dcheck_state(DcheckState state);
654 #if defined(DCHECK_ALWAYS_ON)
656 #define DCHECK_IS_ON() true
657 #define COMPACT_GOOGLE_LOG_EX_DCHECK(ClassName, ...) \
658 COMPACT_GOOGLE_LOG_EX_FATAL(ClassName , ##__VA_ARGS__)
659 #define COMPACT_GOOGLE_LOG_DCHECK COMPACT_GOOGLE_LOG_FATAL
660 const LogSeverity LOG_DCHECK = LOG_FATAL;
662 #else
664 #define COMPACT_GOOGLE_LOG_EX_DCHECK(ClassName, ...) \
665 COMPACT_GOOGLE_LOG_EX_ERROR_REPORT(ClassName , ##__VA_ARGS__)
666 #define COMPACT_GOOGLE_LOG_DCHECK COMPACT_GOOGLE_LOG_ERROR_REPORT
667 const LogSeverity LOG_DCHECK = LOG_ERROR_REPORT;
668 #define DCHECK_IS_ON() \
669 ((::logging::get_dcheck_state() == \
670 ::logging::ENABLE_DCHECK_FOR_NON_OFFICIAL_RELEASE_BUILDS) && \
671 LOG_IS_ON(DCHECK))
673 #endif // defined(DCHECK_ALWAYS_ON)
675 #else // defined(NDEBUG)
677 // On a regular debug build, we want to have DCHECKs enabled.
678 #define COMPACT_GOOGLE_LOG_EX_DCHECK(ClassName, ...) \
679 COMPACT_GOOGLE_LOG_EX_FATAL(ClassName , ##__VA_ARGS__)
680 #define COMPACT_GOOGLE_LOG_DCHECK COMPACT_GOOGLE_LOG_FATAL
681 const LogSeverity LOG_DCHECK = LOG_FATAL;
682 #define DCHECK_IS_ON() true
684 #endif // defined(NDEBUG)
686 #else // ENABLE_DCHECK
688 // These are just dummy values since DCHECK_IS_ON() is always false in
689 // this case.
690 #define COMPACT_GOOGLE_LOG_EX_DCHECK(ClassName, ...) \
691 COMPACT_GOOGLE_LOG_EX_INFO(ClassName , ##__VA_ARGS__)
692 #define COMPACT_GOOGLE_LOG_DCHECK COMPACT_GOOGLE_LOG_INFO
693 const LogSeverity LOG_DCHECK = LOG_INFO;
694 #define DCHECK_IS_ON() false
696 #endif // ENABLE_DCHECK
697 #undef ENABLE_DCHECK
699 // DCHECK et al. make sure to reference |condition| regardless of
700 // whether DCHECKs are enabled; this is so that we don't get unused
701 // variable warnings if the only use of a variable is in a DCHECK.
702 // This behavior is different from DLOG_IF et al.
704 #define DCHECK(condition) \
705 LAZY_STREAM(LOG_STREAM(DCHECK), DCHECK_IS_ON() && !(condition)) \
706 << "Check failed: " #condition ". "
708 #define DPCHECK(condition) \
709 LAZY_STREAM(PLOG_STREAM(DCHECK), DCHECK_IS_ON() && !(condition)) \
710 << "Check failed: " #condition ". "
712 // Helper macro for binary operators.
713 // Don't use this macro directly in your code, use DCHECK_EQ et al below.
714 #define DCHECK_OP(name, op, val1, val2) \
715 if (DCHECK_IS_ON()) \
716 if (std::string* _result = \
717 logging::Check##name##Impl((val1), (val2), \
718 #val1 " " #op " " #val2)) \
719 logging::LogMessage( \
720 __FILE__, __LINE__, ::logging::LOG_DCHECK, \
721 _result).stream()
723 // Equality/Inequality checks - compare two values, and log a
724 // LOG_DCHECK message including the two values when the result is not
725 // as expected. The values must have operator<<(ostream, ...)
726 // defined.
728 // You may append to the error message like so:
729 // DCHECK_NE(1, 2) << ": The world must be ending!";
731 // We are very careful to ensure that each argument is evaluated exactly
732 // once, and that anything which is legal to pass as a function argument is
733 // legal here. In particular, the arguments may be temporary expressions
734 // which will end up being destroyed at the end of the apparent statement,
735 // for example:
736 // DCHECK_EQ(string("abc")[1], 'b');
738 // WARNING: These may not compile correctly if one of the arguments is a pointer
739 // and the other is NULL. To work around this, simply static_cast NULL to the
740 // type of the desired pointer.
742 #define DCHECK_EQ(val1, val2) DCHECK_OP(EQ, ==, val1, val2)
743 #define DCHECK_NE(val1, val2) DCHECK_OP(NE, !=, val1, val2)
744 #define DCHECK_LE(val1, val2) DCHECK_OP(LE, <=, val1, val2)
745 #define DCHECK_LT(val1, val2) DCHECK_OP(LT, < , val1, val2)
746 #define DCHECK_GE(val1, val2) DCHECK_OP(GE, >=, val1, val2)
747 #define DCHECK_GT(val1, val2) DCHECK_OP(GT, > , val1, val2)
749 #define NOTREACHED() DCHECK(false)
751 // Redefine the standard assert to use our nice log files
752 #undef assert
753 #define assert(x) DLOG_ASSERT(x)
755 // This class more or less represents a particular log message. You
756 // create an instance of LogMessage and then stream stuff to it.
757 // When you finish streaming to it, ~LogMessage is called and the
758 // full message gets streamed to the appropriate destination.
760 // You shouldn't actually use LogMessage's constructor to log things,
761 // though. You should use the LOG() macro (and variants thereof)
762 // above.
763 class BASE_EXPORT LogMessage {
764 public:
765 LogMessage(const char* file, int line, LogSeverity severity, int ctr);
767 // Two special constructors that generate reduced amounts of code at
768 // LOG call sites for common cases.
770 // Used for LOG(INFO): Implied are:
771 // severity = LOG_INFO, ctr = 0
773 // Using this constructor instead of the more complex constructor above
774 // saves a couple of bytes per call site.
775 LogMessage(const char* file, int line);
777 // Used for LOG(severity) where severity != INFO. Implied
778 // are: ctr = 0
780 // Using this constructor instead of the more complex constructor above
781 // saves a couple of bytes per call site.
782 LogMessage(const char* file, int line, LogSeverity severity);
784 // A special constructor used for check failures. Takes ownership
785 // of the given string.
786 // Implied severity = LOG_FATAL
787 LogMessage(const char* file, int line, std::string* result);
789 // A special constructor used for check failures, with the option to
790 // specify severity. Takes ownership of the given string.
791 LogMessage(const char* file, int line, LogSeverity severity,
792 std::string* result);
794 ~LogMessage();
796 std::ostream& stream() { return stream_; }
798 private:
799 void Init(const char* file, int line);
801 LogSeverity severity_;
802 std::ostringstream stream_;
803 size_t message_start_; // Offset of the start of the message (past prefix
804 // info).
805 // The file and line information passed in to the constructor.
806 const char* file_;
807 const int line_;
809 #if defined(OS_WIN)
810 // Stores the current value of GetLastError in the constructor and restores
811 // it in the destructor by calling SetLastError.
812 // This is useful since the LogMessage class uses a lot of Win32 calls
813 // that will lose the value of GLE and the code that called the log function
814 // will have lost the thread error value when the log call returns.
815 class SaveLastError {
816 public:
817 SaveLastError();
818 ~SaveLastError();
820 unsigned long get_error() const { return last_error_; }
822 protected:
823 unsigned long last_error_;
826 SaveLastError last_error_;
827 #endif
829 DISALLOW_COPY_AND_ASSIGN(LogMessage);
832 // A non-macro interface to the log facility; (useful
833 // when the logging level is not a compile-time constant).
834 inline void LogAtLevel(int const log_level, std::string const &msg) {
835 LogMessage(__FILE__, __LINE__, log_level).stream() << msg;
838 // This class is used to explicitly ignore values in the conditional
839 // logging macros. This avoids compiler warnings like "value computed
840 // is not used" and "statement has no effect".
841 class LogMessageVoidify {
842 public:
843 LogMessageVoidify() { }
844 // This has to be an operator with a precedence lower than << but
845 // higher than ?:
846 void operator&(std::ostream&) { }
849 #if defined(OS_WIN)
850 typedef unsigned long SystemErrorCode;
851 #elif defined(OS_POSIX)
852 typedef int SystemErrorCode;
853 #endif
855 // Alias for ::GetLastError() on Windows and errno on POSIX. Avoids having to
856 // pull in windows.h just for GetLastError() and DWORD.
857 BASE_EXPORT SystemErrorCode GetLastSystemErrorCode();
859 #if defined(OS_WIN)
860 // Appends a formatted system message of the GetLastError() type.
861 class BASE_EXPORT Win32ErrorLogMessage {
862 public:
863 Win32ErrorLogMessage(const char* file,
864 int line,
865 LogSeverity severity,
866 SystemErrorCode err,
867 const char* module);
869 Win32ErrorLogMessage(const char* file,
870 int line,
871 LogSeverity severity,
872 SystemErrorCode err);
874 // Appends the error message before destructing the encapsulated class.
875 ~Win32ErrorLogMessage();
877 std::ostream& stream() { return log_message_.stream(); }
879 private:
880 SystemErrorCode err_;
881 // Optional name of the module defining the error.
882 const char* module_;
883 LogMessage log_message_;
885 DISALLOW_COPY_AND_ASSIGN(Win32ErrorLogMessage);
887 #elif defined(OS_POSIX)
888 // Appends a formatted system message of the errno type
889 class BASE_EXPORT ErrnoLogMessage {
890 public:
891 ErrnoLogMessage(const char* file,
892 int line,
893 LogSeverity severity,
894 SystemErrorCode err);
896 // Appends the error message before destructing the encapsulated class.
897 ~ErrnoLogMessage();
899 std::ostream& stream() { return log_message_.stream(); }
901 private:
902 SystemErrorCode err_;
903 LogMessage log_message_;
905 DISALLOW_COPY_AND_ASSIGN(ErrnoLogMessage);
907 #endif // OS_WIN
909 // Closes the log file explicitly if open.
910 // NOTE: Since the log file is opened as necessary by the action of logging
911 // statements, there's no guarantee that it will stay closed
912 // after this call.
913 BASE_EXPORT void CloseLogFile();
915 // Async signal safe logging mechanism.
916 BASE_EXPORT void RawLog(int level, const char* message);
918 #define RAW_LOG(level, message) logging::RawLog(logging::LOG_ ## level, message)
920 #define RAW_CHECK(condition) \
921 do { \
922 if (!(condition)) \
923 logging::RawLog(logging::LOG_FATAL, "Check failed: " #condition "\n"); \
924 } while (0)
926 #if defined(OS_WIN)
927 // Returns the default log file path.
928 BASE_EXPORT std::wstring GetLogFileFullPath();
929 #endif
931 } // namespace logging
933 // These functions are provided as a convenience for logging, which is where we
934 // use streams (it is against Google style to use streams in other places). It
935 // is designed to allow you to emit non-ASCII Unicode strings to the log file,
936 // which is normally ASCII. It is relatively slow, so try not to use it for
937 // common cases. Non-ASCII characters will be converted to UTF-8 by these
938 // operators.
939 BASE_EXPORT std::ostream& operator<<(std::ostream& out, const wchar_t* wstr);
940 inline std::ostream& operator<<(std::ostream& out, const std::wstring& wstr) {
941 return out << wstr.c_str();
944 // The NOTIMPLEMENTED() macro annotates codepaths which have
945 // not been implemented yet.
947 // The implementation of this macro is controlled by NOTIMPLEMENTED_POLICY:
948 // 0 -- Do nothing (stripped by compiler)
949 // 1 -- Warn at compile time
950 // 2 -- Fail at compile time
951 // 3 -- Fail at runtime (DCHECK)
952 // 4 -- [default] LOG(ERROR) at runtime
953 // 5 -- LOG(ERROR) at runtime, only once per call-site
955 #ifndef NOTIMPLEMENTED_POLICY
956 #if defined(OS_ANDROID) && defined(OFFICIAL_BUILD)
957 #define NOTIMPLEMENTED_POLICY 0
958 #else
959 // Select default policy: LOG(ERROR)
960 #define NOTIMPLEMENTED_POLICY 4
961 #endif
962 #endif
964 #if defined(COMPILER_GCC)
965 // On Linux, with GCC, we can use __PRETTY_FUNCTION__ to get the demangled name
966 // of the current function in the NOTIMPLEMENTED message.
967 #define NOTIMPLEMENTED_MSG "Not implemented reached in " << __PRETTY_FUNCTION__
968 #else
969 #define NOTIMPLEMENTED_MSG "NOT IMPLEMENTED"
970 #endif
972 #if NOTIMPLEMENTED_POLICY == 0
973 #define NOTIMPLEMENTED() EAT_STREAM_PARAMETERS
974 #elif NOTIMPLEMENTED_POLICY == 1
975 // TODO, figure out how to generate a warning
976 #define NOTIMPLEMENTED() COMPILE_ASSERT(false, NOT_IMPLEMENTED)
977 #elif NOTIMPLEMENTED_POLICY == 2
978 #define NOTIMPLEMENTED() COMPILE_ASSERT(false, NOT_IMPLEMENTED)
979 #elif NOTIMPLEMENTED_POLICY == 3
980 #define NOTIMPLEMENTED() NOTREACHED()
981 #elif NOTIMPLEMENTED_POLICY == 4
982 #define NOTIMPLEMENTED() LOG(ERROR) << NOTIMPLEMENTED_MSG
983 #elif NOTIMPLEMENTED_POLICY == 5
984 #define NOTIMPLEMENTED() do {\
985 static bool logged_once = false;\
986 LOG_IF(ERROR, !logged_once) << NOTIMPLEMENTED_MSG;\
987 logged_once = true;\
988 } while(0);\
989 EAT_STREAM_PARAMETERS
990 #endif
992 #endif // BASE_LOGGING_H_