PageLanguageDetectionTest has the failure rate of 5 - 6% on XP/Vista. Mark it
[chromium-blink-merge.git] / base / logging.h
blob07a0d0f4b796fa06ac4a7cfcb33edc0e9910e013
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.
5 #ifndef BASE_LOGGING_H_
6 #define BASE_LOGGING_H_
8 #include <string>
9 #include <cstring>
10 #include <sstream>
12 #include "base/basictypes.h"
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.
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.
32 // The code for DebugMessage.exe is only one line. In WinMain, do:
33 // MessageBox(NULL, GetCommandLineW(), L"Fatal Error", 0);
35 // If DebugMessage.exe is not found, the logging code will use a normal
36 // MessageBox, potentially causing the problems discussed above.
39 // Instructions
40 // ------------
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.,
45 // LOG(INFO) << "Found " << num_cookies << " cookies";
47 // You can also do conditional logging:
49 // LOG_IF(INFO, num_cookies > 10) << "Got lots of cookies";
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.
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.
59 // There are also "debug mode" logging macros like the ones above:
61 // DLOG(INFO) << "Found cookies";
63 // DLOG_IF(INFO, num_cookies > 10) << "Got lots of cookies";
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.
69 // We also have
71 // LOG_ASSERT(assertion);
72 // DLOG_ASSERT(assertion);
74 // which is syntactic sugar for {,D}LOG_IF(FATAL, assert fails) << assertion;
76 // We also override the standard 'assert' to use 'DLOG_ASSERT'.
78 // Lastly, there is:
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";
87 // which append the last system error to the message in string form (taken from
88 // GetLastError() on Windows and errno on POSIX).
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.
94 // Very important: logging a message at the FATAL severity level causes
95 // the program to terminate (after the message is logged).
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.
101 // There is also the special severity of DFATAL, which logs FATAL in
102 // debug mode, ERROR_REPORT in normal mode.
104 namespace logging {
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 };
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.
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 };
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 };
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.
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
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);
153 // Gets the current log level.
154 int GetMinLogLevel();
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.
160 void SetLogFilterPrefix(const char* filter);
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.
166 void SetLogItems(bool enable_process_id, bool enable_thread_id,
167 bool enable_timestamp, bool enable_tickcount);
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)
173 typedef void (*LogAssertHandlerFunction)(const std::string& str);
174 void 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.
179 typedef void (*LogReportHandlerFunction)(const std::string& str);
180 void SetLogReportHandler(LogReportHandlerFunction handler);
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.
186 typedef bool (*LogMessageHandlerFunction)(int severity, const std::string& str);
187 void SetLogMessageHandler(LogMessageHandlerFunction handler);
189 typedef int LogSeverity;
190 const LogSeverity LOG_INFO = 0;
191 const LogSeverity LOG_WARNING = 1;
192 const LogSeverity LOG_ERROR = 2;
193 const LogSeverity LOG_ERROR_REPORT = 3;
194 const LogSeverity LOG_FATAL = 4;
195 const LogSeverity LOG_NUM_SEVERITIES = 5;
197 // LOG_DFATAL_LEVEL is LOG_FATAL in debug mode, ERROR_REPORT in normal mode
198 #ifdef NDEBUG
199 const LogSeverity LOG_DFATAL_LEVEL = LOG_ERROR_REPORT;
200 #else
201 const LogSeverity LOG_DFATAL_LEVEL = LOG_FATAL;
202 #endif
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__)
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)
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
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.
254 #define LOG(severity) COMPACT_GOOGLE_LOG_ ## severity.stream()
255 #define SYSLOG(severity) LOG(severity)
257 #define LOG_IF(severity, condition) \
258 !(condition) ? (void) 0 : logging::LogMessageVoidify() & LOG(severity)
259 #define SYSLOG_IF(severity, condition) LOG_IF(severity, condition)
261 #define LOG_ASSERT(condition) \
262 LOG_IF(FATAL, !(condition)) << "Assert failed: " #condition ". "
263 #define SYSLOG_ASSERT(condition) \
264 SYSLOG_IF(FATAL, !(condition)) << "Assert failed: " #condition ". "
266 #if defined(OS_WIN)
267 #define LOG_GETLASTERROR(severity) \
268 COMPACT_GOOGLE_LOG_EX_ ## severity(Win32ErrorLogMessage, \
269 ::logging::GetLastSystemErrorCode()).stream()
270 #define LOG_GETLASTERROR_MODULE(severity, module) \
271 COMPACT_GOOGLE_LOG_EX_ ## severity(Win32ErrorLogMessage, \
272 ::logging::GetLastSystemErrorCode(), module).stream()
273 // PLOG is the usual error logging macro for each platform.
274 #define PLOG(severity) LOG_GETLASTERROR(severity)
275 #define DPLOG(severity) DLOG_GETLASTERROR(severity)
276 #elif defined(OS_POSIX)
277 #define LOG_ERRNO(severity) \
278 COMPACT_GOOGLE_LOG_EX_ ## severity(ErrnoLogMessage, \
279 ::logging::GetLastSystemErrorCode()).stream()
280 // PLOG is the usual error logging macro for each platform.
281 #define PLOG(severity) LOG_ERRNO(severity)
282 #define DPLOG(severity) DLOG_ERRNO(severity)
283 // TODO(tschmelcher): Should we add OSStatus logging for Mac?
284 #endif
286 #define PLOG_IF(severity, condition) \
287 !(condition) ? (void) 0 : logging::LogMessageVoidify() & PLOG(severity)
289 // CHECK dies with a fatal error if condition is not true. It is *not*
290 // controlled by NDEBUG, so the check will be executed regardless of
291 // compilation mode.
292 #define CHECK(condition) \
293 LOG_IF(FATAL, !(condition)) << "Check failed: " #condition ". "
295 #define PCHECK(condition) \
296 PLOG_IF(FATAL, !(condition)) << "Check failed: " #condition ". "
298 // A container for a string pointer which can be evaluated to a bool -
299 // true iff the pointer is NULL.
300 struct CheckOpString {
301 CheckOpString(std::string* str) : str_(str) { }
302 // No destructor: if str_ is non-NULL, we're about to LOG(FATAL),
303 // so there's no point in cleaning up str_.
304 operator bool() const { return str_ != NULL; }
305 std::string* str_;
308 // Build the error message string. This is separate from the "Impl"
309 // function template because it is not performance critical and so can
310 // be out of line, while the "Impl" code should be inline.
311 template<class t1, class t2>
312 std::string* MakeCheckOpString(const t1& v1, const t2& v2, const char* names) {
313 std::ostringstream ss;
314 ss << names << " (" << v1 << " vs. " << v2 << ")";
315 std::string* msg = new std::string(ss.str());
316 return msg;
319 extern std::string* MakeCheckOpStringIntInt(int v1, int v2, const char* names);
321 template<int, int>
322 std::string* MakeCheckOpString(const int& v1,
323 const int& v2,
324 const char* names) {
325 return MakeCheckOpStringIntInt(v1, v2, names);
328 // Helper macro for binary operators.
329 // Don't use this macro directly in your code, use CHECK_EQ et al below.
330 #define CHECK_OP(name, op, val1, val2) \
331 if (logging::CheckOpString _result = \
332 logging::Check##name##Impl((val1), (val2), #val1 " " #op " " #val2)) \
333 logging::LogMessage(__FILE__, __LINE__, _result).stream()
335 // Helper functions for string comparisons.
336 // To avoid bloat, the definitions are in logging.cc.
337 #define DECLARE_CHECK_STROP_IMPL(func, expected) \
338 std::string* Check##func##expected##Impl(const char* s1, \
339 const char* s2, \
340 const char* names);
341 DECLARE_CHECK_STROP_IMPL(strcmp, true)
342 DECLARE_CHECK_STROP_IMPL(strcmp, false)
343 DECLARE_CHECK_STROP_IMPL(_stricmp, true)
344 DECLARE_CHECK_STROP_IMPL(_stricmp, false)
345 #undef DECLARE_CHECK_STROP_IMPL
347 // Helper macro for string comparisons.
348 // Don't use this macro directly in your code, use CHECK_STREQ et al below.
349 #define CHECK_STROP(func, op, expected, s1, s2) \
350 while (CheckOpString _result = \
351 logging::Check##func##expected##Impl((s1), (s2), \
352 #s1 " " #op " " #s2)) \
353 LOG(FATAL) << *_result.str_
355 // String (char*) equality/inequality checks.
356 // CASE versions are case-insensitive.
358 // Note that "s1" and "s2" may be temporary strings which are destroyed
359 // by the compiler at the end of the current "full expression"
360 // (e.g. CHECK_STREQ(Foo().c_str(), Bar().c_str())).
362 #define CHECK_STREQ(s1, s2) CHECK_STROP(strcmp, ==, true, s1, s2)
363 #define CHECK_STRNE(s1, s2) CHECK_STROP(strcmp, !=, false, s1, s2)
364 #define CHECK_STRCASEEQ(s1, s2) CHECK_STROP(_stricmp, ==, true, s1, s2)
365 #define CHECK_STRCASENE(s1, s2) CHECK_STROP(_stricmp, !=, false, s1, s2)
367 #define CHECK_INDEX(I,A) CHECK(I < (sizeof(A)/sizeof(A[0])))
368 #define CHECK_BOUND(B,A) CHECK(B <= (sizeof(A)/sizeof(A[0])))
370 #define CHECK_EQ(val1, val2) CHECK_OP(EQ, ==, val1, val2)
371 #define CHECK_NE(val1, val2) CHECK_OP(NE, !=, val1, val2)
372 #define CHECK_LE(val1, val2) CHECK_OP(LE, <=, val1, val2)
373 #define CHECK_LT(val1, val2) CHECK_OP(LT, < , val1, val2)
374 #define CHECK_GE(val1, val2) CHECK_OP(GE, >=, val1, val2)
375 #define CHECK_GT(val1, val2) CHECK_OP(GT, > , val1, val2)
377 // Plus some debug-logging macros that get compiled to nothing for production
379 // DEBUG_MODE is for uses like
380 // if (DEBUG_MODE) foo.CheckThatFoo();
381 // instead of
382 // #ifndef NDEBUG
383 // foo.CheckThatFoo();
384 // #endif
386 // http://crbug.com/16512 is open for a real fix for this. For now, Windows
387 // uses OFFICIAL_BUILD and other platforms use the branding flag when NDEBUG is
388 // defined.
389 #if ( defined(OS_WIN) && defined(OFFICIAL_BUILD)) || \
390 (!defined(OS_WIN) && defined(NDEBUG) && defined(GOOGLE_CHROME_BUILD))
391 // In order to have optimized code for official builds, remove DLOGs and
392 // DCHECKs.
393 #define OMIT_DLOG_AND_DCHECK 1
394 #endif
396 #ifdef OMIT_DLOG_AND_DCHECK
398 #define DLOG(severity) \
399 true ? (void) 0 : logging::LogMessageVoidify() & LOG(severity)
401 #define DLOG_IF(severity, condition) \
402 true ? (void) 0 : logging::LogMessageVoidify() & LOG(severity)
404 #define DLOG_ASSERT(condition) \
405 true ? (void) 0 : LOG_ASSERT(condition)
407 #if defined(OS_WIN)
408 #define DLOG_GETLASTERROR(severity) \
409 true ? (void) 0 : logging::LogMessageVoidify() & LOG_GETLASTERROR(severity)
410 #define DLOG_GETLASTERROR_MODULE(severity, module) \
411 true ? (void) 0 : logging::LogMessageVoidify() & \
412 LOG_GETLASTERROR_MODULE(severity, module)
413 #elif defined(OS_POSIX)
414 #define DLOG_ERRNO(severity) \
415 true ? (void) 0 : logging::LogMessageVoidify() & LOG_ERRNO(severity)
416 #endif
418 #define DPLOG_IF(severity, condition) \
419 true ? (void) 0 : logging::LogMessageVoidify() & PLOG(severity)
421 enum { DEBUG_MODE = 0 };
423 // This macro can be followed by a sequence of stream parameters in
424 // non-debug mode. The DCHECK and friends macros use this so that
425 // the expanded expression DCHECK(foo) << "asdf" is still syntactically
426 // valid, even though the expression will get optimized away.
427 // In order to avoid variable unused warnings for code that only uses a
428 // variable in a CHECK, we make sure to use the macro arguments.
429 #define NDEBUG_EAT_STREAM_PARAMETERS \
430 logging::LogMessage(__FILE__, __LINE__).stream()
432 #define DCHECK(condition) \
433 while (false && (condition)) NDEBUG_EAT_STREAM_PARAMETERS
435 #define DPCHECK(condition) \
436 while (false && (condition)) NDEBUG_EAT_STREAM_PARAMETERS
438 #define DCHECK_EQ(val1, val2) \
439 while (false && (val1) == (val2)) NDEBUG_EAT_STREAM_PARAMETERS
441 #define DCHECK_NE(val1, val2) \
442 while (false && (val1) == (val2)) NDEBUG_EAT_STREAM_PARAMETERS
444 #define DCHECK_LE(val1, val2) \
445 while (false && (val1) == (val2)) NDEBUG_EAT_STREAM_PARAMETERS
447 #define DCHECK_LT(val1, val2) \
448 while (false && (val1) == (val2)) NDEBUG_EAT_STREAM_PARAMETERS
450 #define DCHECK_GE(val1, val2) \
451 while (false && (val1) == (val2)) NDEBUG_EAT_STREAM_PARAMETERS
453 #define DCHECK_GT(val1, val2) \
454 while (false && (val1) == (val2)) NDEBUG_EAT_STREAM_PARAMETERS
456 #define DCHECK_STREQ(str1, str2) \
457 while (false && (str1) == (str2)) NDEBUG_EAT_STREAM_PARAMETERS
459 #define DCHECK_STRCASEEQ(str1, str2) \
460 while (false && (str1) == (str2)) NDEBUG_EAT_STREAM_PARAMETERS
462 #define DCHECK_STRNE(str1, str2) \
463 while (false && (str1) == (str2)) NDEBUG_EAT_STREAM_PARAMETERS
465 #define DCHECK_STRCASENE(str1, str2) \
466 while (false && (str1) == (str2)) NDEBUG_EAT_STREAM_PARAMETERS
468 #else // OMIT_DLOG_AND_DCHECK
470 #ifndef NDEBUG
471 // On a regular debug build, we want to have DCHECKS and DLOGS enabled.
473 #define DLOG(severity) LOG(severity)
474 #define DLOG_IF(severity, condition) LOG_IF(severity, condition)
475 #define DLOG_ASSERT(condition) LOG_ASSERT(condition)
477 #if defined(OS_WIN)
478 #define DLOG_GETLASTERROR(severity) LOG_GETLASTERROR(severity)
479 #define DLOG_GETLASTERROR_MODULE(severity, module) \
480 LOG_GETLASTERROR_MODULE(severity, module)
481 #elif defined(OS_POSIX)
482 #define DLOG_ERRNO(severity) LOG_ERRNO(severity)
483 #endif
485 #define DPLOG_IF(severity, condition) PLOG_IF(severity, condition)
487 // debug-only checking. not executed in NDEBUG mode.
488 enum { DEBUG_MODE = 1 };
489 #define DCHECK(condition) CHECK(condition)
490 #define DPCHECK(condition) PCHECK(condition)
492 // Helper macro for binary operators.
493 // Don't use this macro directly in your code, use DCHECK_EQ et al below.
494 #define DCHECK_OP(name, op, val1, val2) \
495 if (logging::CheckOpString _result = \
496 logging::Check##name##Impl((val1), (val2), #val1 " " #op " " #val2)) \
497 logging::LogMessage(__FILE__, __LINE__, _result).stream()
499 // Helper macro for string comparisons.
500 // Don't use this macro directly in your code, use CHECK_STREQ et al below.
501 #define DCHECK_STROP(func, op, expected, s1, s2) \
502 while (CheckOpString _result = \
503 logging::Check##func##expected##Impl((s1), (s2), \
504 #s1 " " #op " " #s2)) \
505 LOG(FATAL) << *_result.str_
507 // String (char*) equality/inequality checks.
508 // CASE versions are case-insensitive.
510 // Note that "s1" and "s2" may be temporary strings which are destroyed
511 // by the compiler at the end of the current "full expression"
512 // (e.g. DCHECK_STREQ(Foo().c_str(), Bar().c_str())).
514 #define DCHECK_STREQ(s1, s2) DCHECK_STROP(strcmp, ==, true, s1, s2)
515 #define DCHECK_STRNE(s1, s2) DCHECK_STROP(strcmp, !=, false, s1, s2)
516 #define DCHECK_STRCASEEQ(s1, s2) DCHECK_STROP(_stricmp, ==, true, s1, s2)
517 #define DCHECK_STRCASENE(s1, s2) DCHECK_STROP(_stricmp, !=, false, s1, s2)
519 #define DCHECK_INDEX(I,A) DCHECK(I < (sizeof(A)/sizeof(A[0])))
520 #define DCHECK_BOUND(B,A) DCHECK(B <= (sizeof(A)/sizeof(A[0])))
522 #else // NDEBUG
523 // On a regular release build we want to be able to enable DCHECKS through the
524 // command line.
525 #define DLOG(severity) \
526 true ? (void) 0 : logging::LogMessageVoidify() & LOG(severity)
528 #define DLOG_IF(severity, condition) \
529 true ? (void) 0 : logging::LogMessageVoidify() & LOG(severity)
531 #define DLOG_ASSERT(condition) \
532 true ? (void) 0 : LOG_ASSERT(condition)
534 #if defined(OS_WIN)
535 #define DLOG_GETLASTERROR(severity) \
536 true ? (void) 0 : logging::LogMessageVoidify() & LOG_GETLASTERROR(severity)
537 #define DLOG_GETLASTERROR_MODULE(severity, module) \
538 true ? (void) 0 : logging::LogMessageVoidify() & \
539 LOG_GETLASTERROR_MODULE(severity, module)
540 #elif defined(OS_POSIX)
541 #define DLOG_ERRNO(severity) \
542 true ? (void) 0 : logging::LogMessageVoidify() & LOG_ERRNO(severity)
543 #endif
545 #define DPLOG_IF(severity, condition) \
546 true ? (void) 0 : logging::LogMessageVoidify() & PLOG(severity)
548 enum { DEBUG_MODE = 0 };
550 // This macro can be followed by a sequence of stream parameters in
551 // non-debug mode. The DCHECK and friends macros use this so that
552 // the expanded expression DCHECK(foo) << "asdf" is still syntactically
553 // valid, even though the expression will get optimized away.
554 #define NDEBUG_EAT_STREAM_PARAMETERS \
555 logging::LogMessage(__FILE__, __LINE__).stream()
557 // Set to true in InitLogging when we want to enable the dchecks in release.
558 extern bool g_enable_dcheck;
559 #define DCHECK(condition) \
560 !logging::g_enable_dcheck ? void (0) : \
561 LOG_IF(ERROR_REPORT, !(condition)) << "Check failed: " #condition ". "
563 #define DPCHECK(condition) \
564 !logging::g_enable_dcheck ? void (0) : \
565 PLOG_IF(ERROR_REPORT, !(condition)) << "Check failed: " #condition ". "
567 // Helper macro for binary operators.
568 // Don't use this macro directly in your code, use DCHECK_EQ et al below.
569 #define DCHECK_OP(name, op, val1, val2) \
570 if (logging::g_enable_dcheck) \
571 if (logging::CheckOpString _result = \
572 logging::Check##name##Impl((val1), (val2), #val1 " " #op " " #val2)) \
573 logging::LogMessage(__FILE__, __LINE__, logging::LOG_ERROR_REPORT, \
574 _result).stream()
576 #define DCHECK_STREQ(str1, str2) \
577 while (false) NDEBUG_EAT_STREAM_PARAMETERS
579 #define DCHECK_STRCASEEQ(str1, str2) \
580 while (false) NDEBUG_EAT_STREAM_PARAMETERS
582 #define DCHECK_STRNE(str1, str2) \
583 while (false) NDEBUG_EAT_STREAM_PARAMETERS
585 #define DCHECK_STRCASENE(str1, str2) \
586 while (false) NDEBUG_EAT_STREAM_PARAMETERS
588 #endif // NDEBUG
590 // Equality/Inequality checks - compare two values, and log a LOG_FATAL message
591 // including the two values when the result is not as expected. The values
592 // must have operator<<(ostream, ...) defined.
594 // You may append to the error message like so:
595 // DCHECK_NE(1, 2) << ": The world must be ending!";
597 // We are very careful to ensure that each argument is evaluated exactly
598 // once, and that anything which is legal to pass as a function argument is
599 // legal here. In particular, the arguments may be temporary expressions
600 // which will end up being destroyed at the end of the apparent statement,
601 // for example:
602 // DCHECK_EQ(string("abc")[1], 'b');
604 // WARNING: These may not compile correctly if one of the arguments is a pointer
605 // and the other is NULL. To work around this, simply static_cast NULL to the
606 // type of the desired pointer.
608 #define DCHECK_EQ(val1, val2) DCHECK_OP(EQ, ==, val1, val2)
609 #define DCHECK_NE(val1, val2) DCHECK_OP(NE, !=, val1, val2)
610 #define DCHECK_LE(val1, val2) DCHECK_OP(LE, <=, val1, val2)
611 #define DCHECK_LT(val1, val2) DCHECK_OP(LT, < , val1, val2)
612 #define DCHECK_GE(val1, val2) DCHECK_OP(GE, >=, val1, val2)
613 #define DCHECK_GT(val1, val2) DCHECK_OP(GT, > , val1, val2)
615 #endif // OMIT_DLOG_AND_DCHECK
616 #undef OMIT_DLOG_AND_DCHECK
619 // Helper functions for CHECK_OP macro.
620 // The (int, int) specialization works around the issue that the compiler
621 // will not instantiate the template version of the function on values of
622 // unnamed enum type - see comment below.
623 #define DEFINE_CHECK_OP_IMPL(name, op) \
624 template <class t1, class t2> \
625 inline std::string* Check##name##Impl(const t1& v1, const t2& v2, \
626 const char* names) { \
627 if (v1 op v2) return NULL; \
628 else return MakeCheckOpString(v1, v2, names); \
630 inline std::string* Check##name##Impl(int v1, int v2, const char* names) { \
631 if (v1 op v2) return NULL; \
632 else return MakeCheckOpString(v1, v2, names); \
634 DEFINE_CHECK_OP_IMPL(EQ, ==)
635 DEFINE_CHECK_OP_IMPL(NE, !=)
636 DEFINE_CHECK_OP_IMPL(LE, <=)
637 DEFINE_CHECK_OP_IMPL(LT, < )
638 DEFINE_CHECK_OP_IMPL(GE, >=)
639 DEFINE_CHECK_OP_IMPL(GT, > )
640 #undef DEFINE_CHECK_OP_IMPL
642 #define NOTREACHED() DCHECK(false)
644 // Redefine the standard assert to use our nice log files
645 #undef assert
646 #define assert(x) DLOG_ASSERT(x)
648 // This class more or less represents a particular log message. You
649 // create an instance of LogMessage and then stream stuff to it.
650 // When you finish streaming to it, ~LogMessage is called and the
651 // full message gets streamed to the appropriate destination.
653 // You shouldn't actually use LogMessage's constructor to log things,
654 // though. You should use the LOG() macro (and variants thereof)
655 // above.
656 class LogMessage {
657 public:
658 LogMessage(const char* file, int line, LogSeverity severity, int ctr);
660 // Two special constructors that generate reduced amounts of code at
661 // LOG call sites for common cases.
663 // Used for LOG(INFO): Implied are:
664 // severity = LOG_INFO, ctr = 0
666 // Using this constructor instead of the more complex constructor above
667 // saves a couple of bytes per call site.
668 LogMessage(const char* file, int line);
670 // Used for LOG(severity) where severity != INFO. Implied
671 // are: ctr = 0
673 // Using this constructor instead of the more complex constructor above
674 // saves a couple of bytes per call site.
675 LogMessage(const char* file, int line, LogSeverity severity);
677 // A special constructor used for check failures.
678 // Implied severity = LOG_FATAL
679 LogMessage(const char* file, int line, const CheckOpString& result);
681 // A special constructor used for check failures, with the option to
682 // specify severity.
683 LogMessage(const char* file, int line, LogSeverity severity,
684 const CheckOpString& result);
686 ~LogMessage();
688 std::ostream& stream() { return stream_; }
690 private:
691 void Init(const char* file, int line);
693 LogSeverity severity_;
694 std::ostringstream stream_;
695 size_t message_start_; // Offset of the start of the message (past prefix
696 // info).
697 #if defined(OS_WIN)
698 // Stores the current value of GetLastError in the constructor and restores
699 // it in the destructor by calling SetLastError.
700 // This is useful since the LogMessage class uses a lot of Win32 calls
701 // that will lose the value of GLE and the code that called the log function
702 // will have lost the thread error value when the log call returns.
703 class SaveLastError {
704 public:
705 SaveLastError();
706 ~SaveLastError();
708 unsigned long get_error() const { return last_error_; }
710 protected:
711 unsigned long last_error_;
714 SaveLastError last_error_;
715 #endif
717 DISALLOW_COPY_AND_ASSIGN(LogMessage);
720 // A non-macro interface to the log facility; (useful
721 // when the logging level is not a compile-time constant).
722 inline void LogAtLevel(int const log_level, std::string const &msg) {
723 LogMessage(__FILE__, __LINE__, log_level).stream() << msg;
726 // This class is used to explicitly ignore values in the conditional
727 // logging macros. This avoids compiler warnings like "value computed
728 // is not used" and "statement has no effect".
729 class LogMessageVoidify {
730 public:
731 LogMessageVoidify() { }
732 // This has to be an operator with a precedence lower than << but
733 // higher than ?:
734 void operator&(std::ostream&) { }
737 #if defined(OS_WIN)
738 typedef unsigned long SystemErrorCode;
739 #elif defined(OS_POSIX)
740 typedef int SystemErrorCode;
741 #endif
743 // Alias for ::GetLastError() on Windows and errno on POSIX. Avoids having to
744 // pull in windows.h just for GetLastError() and DWORD.
745 SystemErrorCode GetLastSystemErrorCode();
747 #if defined(OS_WIN)
748 // Appends a formatted system message of the GetLastError() type.
749 class Win32ErrorLogMessage {
750 public:
751 Win32ErrorLogMessage(const char* file,
752 int line,
753 LogSeverity severity,
754 SystemErrorCode err,
755 const char* module);
757 Win32ErrorLogMessage(const char* file,
758 int line,
759 LogSeverity severity,
760 SystemErrorCode err);
762 std::ostream& stream() { return log_message_.stream(); }
764 // Appends the error message before destructing the encapsulated class.
765 ~Win32ErrorLogMessage();
767 private:
768 SystemErrorCode err_;
769 // Optional name of the module defining the error.
770 const char* module_;
771 LogMessage log_message_;
773 DISALLOW_COPY_AND_ASSIGN(Win32ErrorLogMessage);
775 #elif defined(OS_POSIX)
776 // Appends a formatted system message of the errno type
777 class ErrnoLogMessage {
778 public:
779 ErrnoLogMessage(const char* file,
780 int line,
781 LogSeverity severity,
782 SystemErrorCode err);
784 std::ostream& stream() { return log_message_.stream(); }
786 // Appends the error message before destructing the encapsulated class.
787 ~ErrnoLogMessage();
789 private:
790 SystemErrorCode err_;
791 LogMessage log_message_;
793 DISALLOW_COPY_AND_ASSIGN(ErrnoLogMessage);
795 #endif // OS_WIN
797 // Closes the log file explicitly if open.
798 // NOTE: Since the log file is opened as necessary by the action of logging
799 // statements, there's no guarantee that it will stay closed
800 // after this call.
801 void CloseLogFile();
803 // Async signal safe logging mechanism.
804 void RawLog(int level, const char* message);
806 #define RAW_LOG(level, message) logging::RawLog(logging::LOG_ ## level, message)
808 #define RAW_CHECK(condition) \
809 do { \
810 if (!(condition)) \
811 logging::RawLog(logging::LOG_FATAL, "Check failed: " #condition "\n"); \
812 } while (0)
814 } // namespace logging
816 // These functions are provided as a convenience for logging, which is where we
817 // use streams (it is against Google style to use streams in other places). It
818 // is designed to allow you to emit non-ASCII Unicode strings to the log file,
819 // which is normally ASCII. It is relatively slow, so try not to use it for
820 // common cases. Non-ASCII characters will be converted to UTF-8 by these
821 // operators.
822 std::ostream& operator<<(std::ostream& out, const wchar_t* wstr);
823 inline std::ostream& operator<<(std::ostream& out, const std::wstring& wstr) {
824 return out << wstr.c_str();
827 // The NOTIMPLEMENTED() macro annotates codepaths which have
828 // not been implemented yet.
830 // The implementation of this macro is controlled by NOTIMPLEMENTED_POLICY:
831 // 0 -- Do nothing (stripped by compiler)
832 // 1 -- Warn at compile time
833 // 2 -- Fail at compile time
834 // 3 -- Fail at runtime (DCHECK)
835 // 4 -- [default] LOG(ERROR) at runtime
836 // 5 -- LOG(ERROR) at runtime, only once per call-site
838 #ifndef NOTIMPLEMENTED_POLICY
839 // Select default policy: LOG(ERROR)
840 #define NOTIMPLEMENTED_POLICY 4
841 #endif
843 #if defined(COMPILER_GCC)
844 // On Linux, with GCC, we can use __PRETTY_FUNCTION__ to get the demangled name
845 // of the current function in the NOTIMPLEMENTED message.
846 #define NOTIMPLEMENTED_MSG "Not implemented reached in " << __PRETTY_FUNCTION__
847 #else
848 #define NOTIMPLEMENTED_MSG "NOT IMPLEMENTED"
849 #endif
851 #if NOTIMPLEMENTED_POLICY == 0
852 #define NOTIMPLEMENTED() ;
853 #elif NOTIMPLEMENTED_POLICY == 1
854 // TODO, figure out how to generate a warning
855 #define NOTIMPLEMENTED() COMPILE_ASSERT(false, NOT_IMPLEMENTED)
856 #elif NOTIMPLEMENTED_POLICY == 2
857 #define NOTIMPLEMENTED() COMPILE_ASSERT(false, NOT_IMPLEMENTED)
858 #elif NOTIMPLEMENTED_POLICY == 3
859 #define NOTIMPLEMENTED() NOTREACHED()
860 #elif NOTIMPLEMENTED_POLICY == 4
861 #define NOTIMPLEMENTED() LOG(ERROR) << NOTIMPLEMENTED_MSG
862 #elif NOTIMPLEMENTED_POLICY == 5
863 #define NOTIMPLEMENTED() do {\
864 static int count = 0;\
865 LOG_IF(ERROR, 0 == count++) << NOTIMPLEMENTED_MSG;\
866 } while(0)
867 #endif
869 #endif // BASE_LOGGING_H_