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