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