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