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