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_REPORT in normal mode. 103 104 namespace 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). 109 enum 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. 122 enum 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. 126 enum 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) 139 void 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? 143 void 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. 151 void SetMinLogLevel(int level); 152 153 // Gets the current log level. 154 int GetMinLogLevel(); 155 156 #if defined(OS_POSIX) && !defined(OS_MACOSX) 157 // Get the file descriptor used for logging. 158 // Returns -1 if none open. 159 // Needed by ZygoteManager. 160 int GetLoggingFileDescriptor(); 161 #endif 162 163 // Sets the log filter prefix. Any log message below LOG_ERROR severity that 164 // doesn't start with this prefix with be silently ignored. The filter defaults 165 // to NULL (everything is logged) if this function is not called. Messages 166 // with severity of LOG_ERROR or higher will not be filtered. 167 void SetLogFilterPrefix(const char* filter); 168 169 // Sets the common items you want to be prepended to each log message. 170 // process and thread IDs default to off, the timestamp defaults to on. 171 // If this function is not called, logging defaults to writing the timestamp 172 // only. 173 void SetLogItems(bool enable_process_id, bool enable_thread_id, 174 bool enable_timestamp, bool enable_tickcount); 175 176 // Sets the Log Assert Handler that will be used to notify of check failures. 177 // The default handler shows a dialog box and then terminate the process, 178 // however clients can use this function to override with their own handling 179 // (e.g. a silent one for Unit Tests) 180 typedef void (*LogAssertHandlerFunction)(const std::string& str); 181 void SetLogAssertHandler(LogAssertHandlerFunction handler); 182 // Sets the Log Report Handler that will be used to notify of check failures 183 // in non-debug mode. The default handler shows a dialog box and continues 184 // the execution, however clients can use this function to override with their 185 // own handling. 186 typedef void (*LogReportHandlerFunction)(const std::string& str); 187 void SetLogReportHandler(LogReportHandlerFunction handler); 188 189 // Sets the Log Message Handler that gets passed every log message before 190 // it's sent to other log destinations (if any). 191 // Returns true to signal that it handled the message and the message 192 // should not be sent to other log destinations. 193 typedef bool (*LogMessageHandlerFunction)(int severity, const std::string& str); 194 void SetLogMessageHandler(LogMessageHandlerFunction handler); 195 196 typedef int LogSeverity; 197 const LogSeverity LOG_INFO = 0; 198 const LogSeverity LOG_WARNING = 1; 199 const LogSeverity LOG_ERROR = 2; 200 const LogSeverity LOG_ERROR_REPORT = 3; 201 const LogSeverity LOG_FATAL = 4; 202 const LogSeverity LOG_NUM_SEVERITIES = 5; 203 204 // LOG_DFATAL_LEVEL is LOG_FATAL in debug mode, ERROR_REPORT in normal mode 205 #ifdef NDEBUG 206 const LogSeverity LOG_DFATAL_LEVEL = LOG_ERROR_REPORT; 207 #else 208 const LogSeverity LOG_DFATAL_LEVEL = LOG_FATAL; 209 #endif 210 211 // A few definitions of macros that don't generate much code. These are used 212 // by LOG() and LOG_IF, etc. Since these are used all over our code, it's 213 // better to have compact code for these operations. 214 #define COMPACT_GOOGLE_LOG_EX_INFO(ClassName, ...) \ 215 logging::ClassName(__FILE__, __LINE__, logging::LOG_INFO , ##__VA_ARGS__) 216 #define COMPACT_GOOGLE_LOG_EX_WARNING(ClassName, ...) \ 217 logging::ClassName(__FILE__, __LINE__, logging::LOG_WARNING , ##__VA_ARGS__) 218 #define COMPACT_GOOGLE_LOG_EX_ERROR(ClassName, ...) \ 219 logging::ClassName(__FILE__, __LINE__, logging::LOG_ERROR , ##__VA_ARGS__) 220 #define COMPACT_GOOGLE_LOG_EX_ERROR_REPORT(ClassName, ...) \ 221 logging::ClassName(__FILE__, __LINE__, \ 222 logging::LOG_ERROR_REPORT , ##__VA_ARGS__) 223 #define COMPACT_GOOGLE_LOG_EX_FATAL(ClassName, ...) \ 224 logging::ClassName(__FILE__, __LINE__, logging::LOG_FATAL , ##__VA_ARGS__) 225 #define COMPACT_GOOGLE_LOG_EX_DFATAL(ClassName, ...) \ 226 logging::ClassName(__FILE__, __LINE__, \ 227 logging::LOG_DFATAL_LEVEL , ##__VA_ARGS__) 228 229 #define COMPACT_GOOGLE_LOG_INFO \ 230 COMPACT_GOOGLE_LOG_EX_INFO(LogMessage) 231 #define COMPACT_GOOGLE_LOG_WARNING \ 232 COMPACT_GOOGLE_LOG_EX_WARNING(LogMessage) 233 #define COMPACT_GOOGLE_LOG_ERROR \ 234 COMPACT_GOOGLE_LOG_EX_ERROR(LogMessage) 235 #define COMPACT_GOOGLE_LOG_ERROR_REPORT \ 236 COMPACT_GOOGLE_LOG_EX_ERROR_REPORT(LogMessage) 237 #define COMPACT_GOOGLE_LOG_FATAL \ 238 COMPACT_GOOGLE_LOG_EX_FATAL(LogMessage) 239 #define COMPACT_GOOGLE_LOG_DFATAL \ 240 COMPACT_GOOGLE_LOG_EX_DFATAL(LogMessage) 241 242 // wingdi.h defines ERROR to be 0. When we call LOG(ERROR), it gets 243 // substituted with 0, and it expands to COMPACT_GOOGLE_LOG_0. To allow us 244 // to keep using this syntax, we define this macro to do the same thing 245 // as COMPACT_GOOGLE_LOG_ERROR, and also define ERROR the same way that 246 // the Windows SDK does for consistency. 247 #define ERROR 0 248 #define COMPACT_GOOGLE_LOG_EX_0(ClassName, ...) \ 249 COMPACT_GOOGLE_LOG_EX_ERROR(ClassName , ##__VA_ARGS__) 250 #define COMPACT_GOOGLE_LOG_0 COMPACT_GOOGLE_LOG_ERROR 251 252 // We use the preprocessor's merging operator, "##", so that, e.g., 253 // LOG(INFO) becomes the token COMPACT_GOOGLE_LOG_INFO. There's some funny 254 // subtle difference between ostream member streaming functions (e.g., 255 // ostream::operator<<(int) and ostream non-member streaming functions 256 // (e.g., ::operator<<(ostream&, string&): it turns out that it's 257 // impossible to stream something like a string directly to an unnamed 258 // ostream. We employ a neat hack by calling the stream() member 259 // function of LogMessage which seems to avoid the problem. 260 261 #define LOG(severity) COMPACT_GOOGLE_LOG_ ## severity.stream() 262 #define SYSLOG(severity) LOG(severity) 263 264 #define LOG_IF(severity, condition) \ 265 !(condition) ? (void) 0 : logging::LogMessageVoidify() & LOG(severity) 266 #define SYSLOG_IF(severity, condition) LOG_IF(severity, condition) 267 268 #define LOG_ASSERT(condition) \ 269 LOG_IF(FATAL, !(condition)) << "Assert failed: " #condition ". " 270 #define SYSLOG_ASSERT(condition) \ 271 SYSLOG_IF(FATAL, !(condition)) << "Assert failed: " #condition ". " 272 273 #if defined(OS_WIN) 274 #define LOG_GETLASTERROR(severity) \ 275 COMPACT_GOOGLE_LOG_EX_ ## severity(Win32ErrorLogMessage, \ 276 ::logging::GetLastSystemErrorCode()).stream() 277 #define LOG_GETLASTERROR_MODULE(severity, module) \ 278 COMPACT_GOOGLE_LOG_EX_ ## severity(Win32ErrorLogMessage, \ 279 ::logging::GetLastSystemErrorCode(), module).stream() 280 // PLOG is the usual error logging macro for each platform. 281 #define PLOG(severity) LOG_GETLASTERROR(severity) 282 #define DPLOG(severity) DLOG_GETLASTERROR(severity) 283 #elif defined(OS_POSIX) 284 #define LOG_ERRNO(severity) \ 285 COMPACT_GOOGLE_LOG_EX_ ## severity(ErrnoLogMessage, \ 286 ::logging::GetLastSystemErrorCode()).stream() 287 // PLOG is the usual error logging macro for each platform. 288 #define PLOG(severity) LOG_ERRNO(severity) 289 #define DPLOG(severity) DLOG_ERRNO(severity) 290 // TODO(tschmelcher): Should we add OSStatus logging for Mac? 291 #endif 292 293 #define PLOG_IF(severity, condition) \ 294 !(condition) ? (void) 0 : logging::LogMessageVoidify() & PLOG(severity) 295 296 // CHECK dies with a fatal error if condition is not true. It is *not* 297 // controlled by NDEBUG, so the check will be executed regardless of 298 // compilation mode. 299 #define CHECK(condition) \ 300 LOG_IF(FATAL, !(condition)) << "Check failed: " #condition ". " 301 302 #define PCHECK(condition) \ 303 PLOG_IF(FATAL, !(condition)) << "Check failed: " #condition ". " 304 305 // A container for a string pointer which can be evaluated to a bool - 306 // true iff the pointer is NULL. 307 struct CheckOpString { 308 CheckOpString(std::string* str) : str_(str) { } 309 // No destructor: if str_ is non-NULL, we're about to LOG(FATAL), 310 // so there's no point in cleaning up str_. 311 operator bool() const { return str_ != NULL; } 312 std::string* str_; 313 }; 314 315 // Build the error message string. This is separate from the "Impl" 316 // function template because it is not performance critical and so can 317 // be out of line, while the "Impl" code should be inline. 318 template<class t1, class t2> 319 std::string* MakeCheckOpString(const t1& v1, const t2& v2, const char* names) { 320 std::ostringstream ss; 321 ss << names << " (" << v1 << " vs. " << v2 << ")"; 322 std::string* msg = new std::string(ss.str()); 323 return msg; 324 } 325 326 extern std::string* MakeCheckOpStringIntInt(int v1, int v2, const char* names); 327 328 template<int, int> 329 std::string* MakeCheckOpString(const int& v1, 330 const int& v2, 331 const char* names) { 332 return MakeCheckOpStringIntInt(v1, v2, names); 333 } 334 335 // Plus some debug-logging macros that get compiled to nothing for production 336 // 337 // DEBUG_MODE is for uses like 338 // if (DEBUG_MODE) foo.CheckThatFoo(); 339 // instead of 340 // #ifndef NDEBUG 341 // foo.CheckThatFoo(); 342 // #endif 343 344 // http://crbug.com/16512 is open for a real fix for this. For now, Windows 345 // uses OFFICIAL_BUILD and other platforms use the branding flag when NDEBUG is 346 // defined. 347 #if ( defined(OS_WIN) && defined(OFFICIAL_BUILD)) || \ 348 (!defined(OS_WIN) && defined(NDEBUG) && defined(GOOGLE_CHROME_BUILD)) 349 // In order to have optimized code for official builds, remove DLOGs and 350 // DCHECKs. 351 #define OMIT_DLOG_AND_DCHECK 1 352 #endif 353 354 #ifdef OMIT_DLOG_AND_DCHECK 355 356 #define DLOG(severity) \ 357 true ? (void) 0 : logging::LogMessageVoidify() & LOG(severity) 358 359 #define DLOG_IF(severity, condition) \ 360 true ? (void) 0 : logging::LogMessageVoidify() & LOG(severity) 361 362 #define DLOG_ASSERT(condition) \ 363 true ? (void) 0 : LOG_ASSERT(condition) 364 365 #if defined(OS_WIN) 366 #define DLOG_GETLASTERROR(severity) \ 367 true ? (void) 0 : logging::LogMessageVoidify() & LOG_GETLASTERROR(severity) 368 #define DLOG_GETLASTERROR_MODULE(severity, module) \ 369 true ? (void) 0 : logging::LogMessageVoidify() & \ 370 LOG_GETLASTERROR_MODULE(severity, module) 371 #elif defined(OS_POSIX) 372 #define DLOG_ERRNO(severity) \ 373 true ? (void) 0 : logging::LogMessageVoidify() & LOG_ERRNO(severity) 374 #endif 375 376 #define DPLOG_IF(severity, condition) \ 377 true ? (void) 0 : logging::LogMessageVoidify() & PLOG(severity) 378 379 enum { DEBUG_MODE = 0 }; 380 381 // This macro can be followed by a sequence of stream parameters in 382 // non-debug mode. The DCHECK and friends macros use this so that 383 // the expanded expression DCHECK(foo) << "asdf" is still syntactically 384 // valid, even though the expression will get optimized away. 385 // In order to avoid variable unused warnings for code that only uses a 386 // variable in a CHECK, we make sure to use the macro arguments. 387 #define NDEBUG_EAT_STREAM_PARAMETERS \ 388 logging::LogMessage(__FILE__, __LINE__).stream() 389 390 #define DCHECK(condition) \ 391 while (false && (condition)) NDEBUG_EAT_STREAM_PARAMETERS 392 393 #define DPCHECK(condition) \ 394 while (false && (condition)) NDEBUG_EAT_STREAM_PARAMETERS 395 396 #define DCHECK_EQ(val1, val2) \ 397 while (false && (val1) == (val2)) NDEBUG_EAT_STREAM_PARAMETERS 398 399 #define DCHECK_NE(val1, val2) \ 400 while (false && (val1) == (val2)) NDEBUG_EAT_STREAM_PARAMETERS 401 402 #define DCHECK_LE(val1, val2) \ 403 while (false && (val1) == (val2)) NDEBUG_EAT_STREAM_PARAMETERS 404 405 #define DCHECK_LT(val1, val2) \ 406 while (false && (val1) == (val2)) NDEBUG_EAT_STREAM_PARAMETERS 407 408 #define DCHECK_GE(val1, val2) \ 409 while (false && (val1) == (val2)) NDEBUG_EAT_STREAM_PARAMETERS 410 411 #define DCHECK_GT(val1, val2) \ 412 while (false && (val1) == (val2)) NDEBUG_EAT_STREAM_PARAMETERS 413 414 #define DCHECK_STREQ(str1, str2) \ 415 while (false && (str1) == (str2)) NDEBUG_EAT_STREAM_PARAMETERS 416 417 #define DCHECK_STRCASEEQ(str1, str2) \ 418 while (false && (str1) == (str2)) NDEBUG_EAT_STREAM_PARAMETERS 419 420 #define DCHECK_STRNE(str1, str2) \ 421 while (false && (str1) == (str2)) NDEBUG_EAT_STREAM_PARAMETERS 422 423 #define DCHECK_STRCASENE(str1, str2) \ 424 while (false && (str1) == (str2)) NDEBUG_EAT_STREAM_PARAMETERS 425 426 #else // OMIT_DLOG_AND_DCHECK 427 428 #ifndef NDEBUG 429 // On a regular debug build, we want to have DCHECKS and DLOGS enabled. 430 431 #define DLOG(severity) LOG(severity) 432 #define DLOG_IF(severity, condition) LOG_IF(severity, condition) 433 #define DLOG_ASSERT(condition) LOG_ASSERT(condition) 434 435 #if defined(OS_WIN) 436 #define DLOG_GETLASTERROR(severity) LOG_GETLASTERROR(severity) 437 #define DLOG_GETLASTERROR_MODULE(severity, module) \ 438 LOG_GETLASTERROR_MODULE(severity, module) 439 #elif defined(OS_POSIX) 440 #define DLOG_ERRNO(severity) LOG_ERRNO(severity) 441 #endif 442 443 #define DPLOG_IF(severity, condition) PLOG_IF(severity, condition) 444 445 // debug-only checking. not executed in NDEBUG mode. 446 enum { DEBUG_MODE = 1 }; 447 #define DCHECK(condition) \ 448 LOG_IF(FATAL, !(condition)) << "Check failed: " #condition ". " 449 450 #define DPCHECK(condition) \ 451 PLOG_IF(FATAL, !(condition)) << "Check failed: " #condition ". " 452 453 // Helper macro for binary operators. 454 // Don't use this macro directly in your code, use DCHECK_EQ et al below. 455 #define DCHECK_OP(name, op, val1, val2) \ 456 if (logging::CheckOpString _result = \ 457 logging::Check##name##Impl((val1), (val2), #val1 " " #op " " #val2)) \ 458 logging::LogMessage(__FILE__, __LINE__, _result).stream() 459 460 // Helper functions for string comparisons. 461 // To avoid bloat, the definitions are in logging.cc. 462 #define DECLARE_DCHECK_STROP_IMPL(func, expected) \ 463 std::string* Check##func##expected##Impl(const char* s1, \ 464 const char* s2, \ 465 const char* names); 466 DECLARE_DCHECK_STROP_IMPL(strcmp, true) 467 DECLARE_DCHECK_STROP_IMPL(strcmp, false) 468 DECLARE_DCHECK_STROP_IMPL(_stricmp, true) 469 DECLARE_DCHECK_STROP_IMPL(_stricmp, false) 470 #undef DECLARE_DCHECK_STROP_IMPL 471 472 // Helper macro for string comparisons. 473 // Don't use this macro directly in your code, use CHECK_STREQ et al below. 474 #define DCHECK_STROP(func, op, expected, s1, s2) \ 475 while (CheckOpString _result = \ 476 logging::Check##func##expected##Impl((s1), (s2), \ 477 #s1 " " #op " " #s2)) \ 478 LOG(FATAL) << *_result.str_ 479 480 // String (char*) equality/inequality checks. 481 // CASE versions are case-insensitive. 482 // 483 // Note that "s1" and "s2" may be temporary strings which are destroyed 484 // by the compiler at the end of the current "full expression" 485 // (e.g. DCHECK_STREQ(Foo().c_str(), Bar().c_str())). 486 487 #define DCHECK_STREQ(s1, s2) DCHECK_STROP(strcmp, ==, true, s1, s2) 488 #define DCHECK_STRNE(s1, s2) DCHECK_STROP(strcmp, !=, false, s1, s2) 489 #define DCHECK_STRCASEEQ(s1, s2) DCHECK_STROP(_stricmp, ==, true, s1, s2) 490 #define DCHECK_STRCASENE(s1, s2) DCHECK_STROP(_stricmp, !=, false, s1, s2) 491 492 #define DCHECK_INDEX(I,A) DCHECK(I < (sizeof(A)/sizeof(A[0]))) 493 #define DCHECK_BOUND(B,A) DCHECK(B <= (sizeof(A)/sizeof(A[0]))) 494 495 #else // NDEBUG 496 // On a regular release build we want to be able to enable DCHECKS through the 497 // command line. 498 #define DLOG(severity) \ 499 true ? (void) 0 : logging::LogMessageVoidify() & LOG(severity) 500 501 #define DLOG_IF(severity, condition) \ 502 true ? (void) 0 : logging::LogMessageVoidify() & LOG(severity) 503 504 #define DLOG_ASSERT(condition) \ 505 true ? (void) 0 : LOG_ASSERT(condition) 506 507 #if defined(OS_WIN) 508 #define DLOG_GETLASTERROR(severity) \ 509 true ? (void) 0 : logging::LogMessageVoidify() & LOG_GETLASTERROR(severity) 510 #define DLOG_GETLASTERROR_MODULE(severity, module) \ 511 true ? (void) 0 : logging::LogMessageVoidify() & \ 512 LOG_GETLASTERROR_MODULE(severity, module) 513 #elif defined(OS_POSIX) 514 #define DLOG_ERRNO(severity) \ 515 true ? (void) 0 : logging::LogMessageVoidify() & LOG_ERRNO(severity) 516 #endif 517 518 #define DPLOG_IF(severity, condition) \ 519 true ? (void) 0 : logging::LogMessageVoidify() & PLOG(severity) 520 521 enum { DEBUG_MODE = 0 }; 522 523 // This macro can be followed by a sequence of stream parameters in 524 // non-debug mode. The DCHECK and friends macros use this so that 525 // the expanded expression DCHECK(foo) << "asdf" is still syntactically 526 // valid, even though the expression will get optimized away. 527 #define NDEBUG_EAT_STREAM_PARAMETERS \ 528 logging::LogMessage(__FILE__, __LINE__).stream() 529 530 // Set to true in InitLogging when we want to enable the dchecks in release. 531 extern bool g_enable_dcheck; 532 #define DCHECK(condition) \ 533 !logging::g_enable_dcheck ? void (0) : \ 534 LOG_IF(ERROR_REPORT, !(condition)) << "Check failed: " #condition ". " 535 536 #define DPCHECK(condition) \ 537 !logging::g_enable_dcheck ? void (0) : \ 538 PLOG_IF(ERROR_REPORT, !(condition)) << "Check failed: " #condition ". " 539 540 // Helper macro for binary operators. 541 // Don't use this macro directly in your code, use DCHECK_EQ et al below. 542 #define DCHECK_OP(name, op, val1, val2) \ 543 if (logging::g_enable_dcheck) \ 544 if (logging::CheckOpString _result = \ 545 logging::Check##name##Impl((val1), (val2), #val1 " " #op " " #val2)) \ 546 logging::LogMessage(__FILE__, __LINE__, logging::LOG_ERROR_REPORT, \ 547 _result).stream() 548 549 #define DCHECK_STREQ(str1, str2) \ 550 while (false) NDEBUG_EAT_STREAM_PARAMETERS 551 552 #define DCHECK_STRCASEEQ(str1, str2) \ 553 while (false) NDEBUG_EAT_STREAM_PARAMETERS 554 555 #define DCHECK_STRNE(str1, str2) \ 556 while (false) NDEBUG_EAT_STREAM_PARAMETERS 557 558 #define DCHECK_STRCASENE(str1, str2) \ 559 while (false) NDEBUG_EAT_STREAM_PARAMETERS 560 561 #endif // NDEBUG 562 563 // Helper functions for DCHECK_OP macro. 564 // The (int, int) specialization works around the issue that the compiler 565 // will not instantiate the template version of the function on values of 566 // unnamed enum type - see comment below. 567 #define DEFINE_DCHECK_OP_IMPL(name, op) \ 568 template <class t1, class t2> \ 569 inline std::string* Check##name##Impl(const t1& v1, const t2& v2, \ 570 const char* names) { \ 571 if (v1 op v2) return NULL; \ 572 else return MakeCheckOpString(v1, v2, names); \ 573 } \ 574 inline std::string* Check##name##Impl(int v1, int v2, const char* names) { \ 575 if (v1 op v2) return NULL; \ 576 else return MakeCheckOpString(v1, v2, names); \ 577 } 578 DEFINE_DCHECK_OP_IMPL(EQ, ==) 579 DEFINE_DCHECK_OP_IMPL(NE, !=) 580 DEFINE_DCHECK_OP_IMPL(LE, <=) 581 DEFINE_DCHECK_OP_IMPL(LT, < ) 582 DEFINE_DCHECK_OP_IMPL(GE, >=) 583 DEFINE_DCHECK_OP_IMPL(GT, > ) 584 #undef DEFINE_DCHECK_OP_IMPL 585 586 // Equality/Inequality checks - compare two values, and log a LOG_FATAL message 587 // including the two values when the result is not as expected. The values 588 // must have operator<<(ostream, ...) defined. 589 // 590 // You may append to the error message like so: 591 // DCHECK_NE(1, 2) << ": The world must be ending!"; 592 // 593 // We are very careful to ensure that each argument is evaluated exactly 594 // once, and that anything which is legal to pass as a function argument is 595 // legal here. In particular, the arguments may be temporary expressions 596 // which will end up being destroyed at the end of the apparent statement, 597 // for example: 598 // DCHECK_EQ(string("abc")[1], 'b'); 599 // 600 // WARNING: These may not compile correctly if one of the arguments is a pointer 601 // and the other is NULL. To work around this, simply static_cast NULL to the 602 // type of the desired pointer. 603 604 #define DCHECK_EQ(val1, val2) DCHECK_OP(EQ, ==, val1, val2) 605 #define DCHECK_NE(val1, val2) DCHECK_OP(NE, !=, val1, val2) 606 #define DCHECK_LE(val1, val2) DCHECK_OP(LE, <=, val1, val2) 607 #define DCHECK_LT(val1, val2) DCHECK_OP(LT, < , val1, val2) 608 #define DCHECK_GE(val1, val2) DCHECK_OP(GE, >=, val1, val2) 609 #define DCHECK_GT(val1, val2) DCHECK_OP(GT, > , val1, val2) 610 611 #endif // OMIT_DLOG_AND_DCHECK 612 #undef OMIT_DLOG_AND_DCHECK 613 614 #define NOTREACHED() DCHECK(false) 615 616 // Redefine the standard assert to use our nice log files 617 #undef assert 618 #define assert(x) DLOG_ASSERT(x) 619 620 // This class more or less represents a particular log message. You 621 // create an instance of LogMessage and then stream stuff to it. 622 // When you finish streaming to it, ~LogMessage is called and the 623 // full message gets streamed to the appropriate destination. 624 // 625 // You shouldn't actually use LogMessage's constructor to log things, 626 // though. You should use the LOG() macro (and variants thereof) 627 // above. 628 class LogMessage { 629 public: 630 LogMessage(const char* file, int line, LogSeverity severity, int ctr); 631 632 // Two special constructors that generate reduced amounts of code at 633 // LOG call sites for common cases. 634 // 635 // Used for LOG(INFO): Implied are: 636 // severity = LOG_INFO, ctr = 0 637 // 638 // Using this constructor instead of the more complex constructor above 639 // saves a couple of bytes per call site. 640 LogMessage(const char* file, int line); 641 642 // Used for LOG(severity) where severity != INFO. Implied 643 // are: ctr = 0 644 // 645 // Using this constructor instead of the more complex constructor above 646 // saves a couple of bytes per call site. 647 LogMessage(const char* file, int line, LogSeverity severity); 648 649 // A special constructor used for check failures. 650 // Implied severity = LOG_FATAL 651 LogMessage(const char* file, int line, const CheckOpString& result); 652 653 // A special constructor used for check failures, with the option to 654 // specify severity. 655 LogMessage(const char* file, int line, LogSeverity severity, 656 const CheckOpString& result); 657 658 ~LogMessage(); 659 660 std::ostream& stream() { return stream_; } 661 662 private: 663 void Init(const char* file, int line); 664 665 LogSeverity severity_; 666 std::ostringstream stream_; 667 size_t message_start_; // Offset of the start of the message (past prefix 668 // info). 669 #if defined(OS_WIN) 670 // Stores the current value of GetLastError in the constructor and restores 671 // it in the destructor by calling SetLastError. 672 // This is useful since the LogMessage class uses a lot of Win32 calls 673 // that will lose the value of GLE and the code that called the log function 674 // will have lost the thread error value when the log call returns. 675 class SaveLastError { 676 public: 677 SaveLastError(); 678 ~SaveLastError(); 679 680 unsigned long get_error() const { return last_error_; } 681 682 protected: 683 unsigned long last_error_; 684 }; 685 686 SaveLastError last_error_; 687 #endif 688 689 DISALLOW_COPY_AND_ASSIGN(LogMessage); 690 }; 691 692 // A non-macro interface to the log facility; (useful 693 // when the logging level is not a compile-time constant). 694 inline void LogAtLevel(int const log_level, std::string const &msg) { 695 LogMessage(__FILE__, __LINE__, log_level).stream() << msg; 696 } 697 698 // This class is used to explicitly ignore values in the conditional 699 // logging macros. This avoids compiler warnings like "value computed 700 // is not used" and "statement has no effect". 701 class LogMessageVoidify { 702 public: 703 LogMessageVoidify() { } 704 // This has to be an operator with a precedence lower than << but 705 // higher than ?: 706 void operator&(std::ostream&) { } 707 }; 708 709 #if defined(OS_WIN) 710 typedef unsigned long SystemErrorCode; 711 #elif defined(OS_POSIX) 712 typedef int SystemErrorCode; 713 #endif 714 715 // Alias for ::GetLastError() on Windows and errno on POSIX. Avoids having to 716 // pull in windows.h just for GetLastError() and DWORD. 717 SystemErrorCode GetLastSystemErrorCode(); 718 719 #if defined(OS_WIN) 720 // Appends a formatted system message of the GetLastError() type. 721 class Win32ErrorLogMessage { 722 public: 723 Win32ErrorLogMessage(const char* file, 724 int line, 725 LogSeverity severity, 726 SystemErrorCode err, 727 const char* module); 728 729 Win32ErrorLogMessage(const char* file, 730 int line, 731 LogSeverity severity, 732 SystemErrorCode err); 733 734 std::ostream& stream() { return log_message_.stream(); } 735 736 // Appends the error message before destructing the encapsulated class. 737 ~Win32ErrorLogMessage(); 738 739 private: 740 SystemErrorCode err_; 741 // Optional name of the module defining the error. 742 const char* module_; 743 LogMessage log_message_; 744 745 DISALLOW_COPY_AND_ASSIGN(Win32ErrorLogMessage); 746 }; 747 #elif defined(OS_POSIX) 748 // Appends a formatted system message of the errno type 749 class ErrnoLogMessage { 750 public: 751 ErrnoLogMessage(const char* file, 752 int line, 753 LogSeverity severity, 754 SystemErrorCode err); 755 756 std::ostream& stream() { return log_message_.stream(); } 757 758 // Appends the error message before destructing the encapsulated class. 759 ~ErrnoLogMessage(); 760 761 private: 762 SystemErrorCode err_; 763 LogMessage log_message_; 764 765 DISALLOW_COPY_AND_ASSIGN(ErrnoLogMessage); 766 }; 767 #endif // OS_WIN 768 769 // Closes the log file explicitly if open. 770 // NOTE: Since the log file is opened as necessary by the action of logging 771 // statements, there's no guarantee that it will stay closed 772 // after this call. 773 void CloseLogFile(); 774 775 // Async signal safe logging mechanism. 776 void RawLog(int level, const char* message); 777 778 #define RAW_LOG(level, message) logging::RawLog(logging::LOG_ ## level, message) 779 780 #define RAW_CHECK(condition) \ 781 do { \ 782 if (!(condition)) \ 783 logging::RawLog(logging::LOG_FATAL, "Check failed: " #condition "\n"); \ 784 } while (0) 785 786 } // namespace logging 787 788 // These functions are provided as a convenience for logging, which is where we 789 // use streams (it is against Google style to use streams in other places). It 790 // is designed to allow you to emit non-ASCII Unicode strings to the log file, 791 // which is normally ASCII. It is relatively slow, so try not to use it for 792 // common cases. Non-ASCII characters will be converted to UTF-8 by these 793 // operators. 794 std::ostream& operator<<(std::ostream& out, const wchar_t* wstr); 795 inline std::ostream& operator<<(std::ostream& out, const std::wstring& wstr) { 796 return out << wstr.c_str(); 797 } 798 799 // The NOTIMPLEMENTED() macro annotates codepaths which have 800 // not been implemented yet. 801 // 802 // The implementation of this macro is controlled by NOTIMPLEMENTED_POLICY: 803 // 0 -- Do nothing (stripped by compiler) 804 // 1 -- Warn at compile time 805 // 2 -- Fail at compile time 806 // 3 -- Fail at runtime (DCHECK) 807 // 4 -- [default] LOG(ERROR) at runtime 808 // 5 -- LOG(ERROR) at runtime, only once per call-site 809 810 #ifndef NOTIMPLEMENTED_POLICY 811 // Select default policy: LOG(ERROR) 812 #define NOTIMPLEMENTED_POLICY 4 813 #endif 814 815 #if defined(COMPILER_GCC) 816 // On Linux, with GCC, we can use __PRETTY_FUNCTION__ to get the demangled name 817 // of the current function in the NOTIMPLEMENTED message. 818 #define NOTIMPLEMENTED_MSG "Not implemented reached in " << __PRETTY_FUNCTION__ 819 #else 820 #define NOTIMPLEMENTED_MSG "NOT IMPLEMENTED" 821 #endif 822 823 #if NOTIMPLEMENTED_POLICY == 0 824 #define NOTIMPLEMENTED() ; 825 #elif NOTIMPLEMENTED_POLICY == 1 826 // TODO, figure out how to generate a warning 827 #define NOTIMPLEMENTED() COMPILE_ASSERT(false, NOT_IMPLEMENTED) 828 #elif NOTIMPLEMENTED_POLICY == 2 829 #define NOTIMPLEMENTED() COMPILE_ASSERT(false, NOT_IMPLEMENTED) 830 #elif NOTIMPLEMENTED_POLICY == 3 831 #define NOTIMPLEMENTED() NOTREACHED() 832 #elif NOTIMPLEMENTED_POLICY == 4 833 #define NOTIMPLEMENTED() LOG(ERROR) << NOTIMPLEMENTED_MSG 834 #elif NOTIMPLEMENTED_POLICY == 5 835 #define NOTIMPLEMENTED() do {\ 836 static int count = 0;\ 837 LOG_IF(ERROR, 0 == count++) << NOTIMPLEMENTED_MSG;\ 838 } while(0) 839 #endif 840 841 #endif // BASE_LOGGING_H_ 842