blob: c63d827984ffa86a26790e97fa8d23af768b17a9 [file] [log] [blame]
license.botbf09a502008-08-24 00:55:551// 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.
initial.commitd7cae122008-07-26 21:49:384
[email protected]39be4242008-08-07 18:31:405#ifndef BASE_LOGGING_H_
6#define BASE_LOGGING_H_
[email protected]32b76ef2010-07-26 23:08:247#pragma once
initial.commitd7cae122008-07-26 21:49:388
9#include <string>
10#include <cstring>
11#include <sstream>
12
13#include "base/basictypes.h"
initial.commitd7cae122008-07-26 21:49:3814
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// We also override the standard 'assert' to use 'DLOG_ASSERT'.
78//
[email protected]d8617a62009-10-09 23:52:2079// Lastly, there is:
80//
81// PLOG(ERROR) << "Couldn't do foo";
82// DPLOG(ERROR) << "Couldn't do foo";
83// PLOG_IF(ERROR, cond) << "Couldn't do foo";
84// DPLOG_IF(ERROR, cond) << "Couldn't do foo";
85// PCHECK(condition) << "Couldn't do foo";
86// DPCHECK(condition) << "Couldn't do foo";
87//
88// which append the last system error to the message in string form (taken from
89// GetLastError() on Windows and errno on POSIX).
90//
initial.commitd7cae122008-07-26 21:49:3891// The supported severity levels for macros that allow you to specify one
[email protected]fb62a532009-02-12 01:19:0592// are (in increasing order of severity) INFO, WARNING, ERROR, ERROR_REPORT,
93// and FATAL.
initial.commitd7cae122008-07-26 21:49:3894//
95// Very important: logging a message at the FATAL severity level causes
96// the program to terminate (after the message is logged).
[email protected]fb62a532009-02-12 01:19:0597//
98// Note the special severity of ERROR_REPORT only available/relevant in normal
99// mode, which displays error dialog without terminating the program. There is
100// no error dialog for severity ERROR or below in normal mode.
101//
102// There is also the special severity of DFATAL, which logs FATAL in
[email protected]081bd4c2010-06-24 01:01:04103// debug mode, ERROR in normal mode.
initial.commitd7cae122008-07-26 21:49:38104
105namespace logging {
106
107// Where to record logging output? A flat file and/or system debug log via
[email protected]88aa41e82008-11-18 00:59:04108// OutputDebugString. Defaults on Windows to LOG_ONLY_TO_FILE, and on
109// POSIX to LOG_ONLY_TO_SYSTEM_DEBUG_LOG (aka stderr).
initial.commitd7cae122008-07-26 21:49:38110enum LoggingDestination { LOG_NONE,
111 LOG_ONLY_TO_FILE,
112 LOG_ONLY_TO_SYSTEM_DEBUG_LOG,
113 LOG_TO_BOTH_FILE_AND_SYSTEM_DEBUG_LOG };
114
115// Indicates that the log file should be locked when being written to.
116// Often, there is no locking, which is fine for a single threaded program.
117// If logging is being done from multiple threads or there can be more than
118// one process doing the logging, the file should be locked during writes to
119// make each log outut atomic. Other writers will block.
120//
121// All processes writing to the log file must have their locking set for it to
122// work properly. Defaults to DONT_LOCK_LOG_FILE.
123enum LogLockingState { LOCK_LOG_FILE, DONT_LOCK_LOG_FILE };
124
125// On startup, should we delete or append to an existing log file (if any)?
126// Defaults to APPEND_TO_OLD_LOG_FILE.
127enum OldFileDeletionState { DELETE_OLD_LOG_FILE, APPEND_TO_OLD_LOG_FILE };
128
129// Sets the log file name and other global logging state. Calling this function
130// is recommended, and is normally done at the beginning of application init.
131// If you don't call it, all the flags will be initialized to their default
132// values, and there is a race condition that may leak a critical section
133// object if two threads try to do the first log at the same time.
134// See the definition of the enums above for descriptions and default values.
135//
136// The default log file is initialized to "debug.log" in the application
137// directory. You probably don't want this, especially since the program
138// directory may not be writable on an enduser's system.
[email protected]39be4242008-08-07 18:31:40139#if defined(OS_WIN)
initial.commitd7cae122008-07-26 21:49:38140void InitLogging(const wchar_t* log_file, LoggingDestination logging_dest,
141 LogLockingState lock_log, OldFileDeletionState delete_old);
[email protected]39be4242008-08-07 18:31:40142#elif defined(OS_POSIX)
initial.commitd7cae122008-07-26 21:49:38143// TODO(avi): do we want to do a unification of character types here?
144void InitLogging(const char* log_file, LoggingDestination logging_dest,
145 LogLockingState lock_log, OldFileDeletionState delete_old);
146#endif
147
148// Sets the log level. Anything at or above this level will be written to the
149// log file/displayed to the user (if applicable). Anything below this level
150// will be silently ignored. The log level defaults to 0 (everything is logged)
151// if this function is not called.
152void SetMinLogLevel(int level);
153
[email protected]8a2986ca2009-04-10 19:13:42154// Gets the current log level.
initial.commitd7cae122008-07-26 21:49:38155int GetMinLogLevel();
156
157// Sets the log filter prefix. Any log message below LOG_ERROR severity that
158// doesn't start with this prefix with be silently ignored. The filter defaults
159// to NULL (everything is logged) if this function is not called. Messages
160// with severity of LOG_ERROR or higher will not be filtered.
161void SetLogFilterPrefix(const char* filter);
162
163// Sets the common items you want to be prepended to each log message.
164// process and thread IDs default to off, the timestamp defaults to on.
165// If this function is not called, logging defaults to writing the timestamp
166// only.
167void SetLogItems(bool enable_process_id, bool enable_thread_id,
168 bool enable_timestamp, bool enable_tickcount);
169
170// Sets the Log Assert Handler that will be used to notify of check failures.
[email protected]fb62a532009-02-12 01:19:05171// The default handler shows a dialog box and then terminate the process,
172// however clients can use this function to override with their own handling
173// (e.g. a silent one for Unit Tests)
initial.commitd7cae122008-07-26 21:49:38174typedef void (*LogAssertHandlerFunction)(const std::string& str);
175void SetLogAssertHandler(LogAssertHandlerFunction handler);
[email protected]fb62a532009-02-12 01:19:05176// Sets the Log Report Handler that will be used to notify of check failures
177// in non-debug mode. The default handler shows a dialog box and continues
178// the execution, however clients can use this function to override with their
179// own handling.
180typedef void (*LogReportHandlerFunction)(const std::string& str);
181void SetLogReportHandler(LogReportHandlerFunction handler);
initial.commitd7cae122008-07-26 21:49:38182
[email protected]2b07b8412009-11-25 15:26:34183// Sets the Log Message Handler that gets passed every log message before
184// it's sent to other log destinations (if any).
185// Returns true to signal that it handled the message and the message
186// should not be sent to other log destinations.
187typedef bool (*LogMessageHandlerFunction)(int severity, const std::string& str);
188void SetLogMessageHandler(LogMessageHandlerFunction handler);
189
initial.commitd7cae122008-07-26 21:49:38190typedef int LogSeverity;
191const LogSeverity LOG_INFO = 0;
192const LogSeverity LOG_WARNING = 1;
193const LogSeverity LOG_ERROR = 2;
[email protected]fb62a532009-02-12 01:19:05194const LogSeverity LOG_ERROR_REPORT = 3;
195const LogSeverity LOG_FATAL = 4;
196const LogSeverity LOG_NUM_SEVERITIES = 5;
initial.commitd7cae122008-07-26 21:49:38197
[email protected]081bd4c2010-06-24 01:01:04198// LOG_DFATAL_LEVEL is LOG_FATAL in debug mode, ERROR in normal mode
initial.commitd7cae122008-07-26 21:49:38199#ifdef NDEBUG
[email protected]081bd4c2010-06-24 01:01:04200const LogSeverity LOG_DFATAL_LEVEL = LOG_ERROR;
initial.commitd7cae122008-07-26 21:49:38201#else
202const LogSeverity LOG_DFATAL_LEVEL = LOG_FATAL;
203#endif
204
205// A few definitions of macros that don't generate much code. These are used
206// by LOG() and LOG_IF, etc. Since these are used all over our code, it's
207// better to have compact code for these operations.
[email protected]d8617a62009-10-09 23:52:20208#define COMPACT_GOOGLE_LOG_EX_INFO(ClassName, ...) \
209 logging::ClassName(__FILE__, __LINE__, logging::LOG_INFO , ##__VA_ARGS__)
210#define COMPACT_GOOGLE_LOG_EX_WARNING(ClassName, ...) \
211 logging::ClassName(__FILE__, __LINE__, logging::LOG_WARNING , ##__VA_ARGS__)
212#define COMPACT_GOOGLE_LOG_EX_ERROR(ClassName, ...) \
213 logging::ClassName(__FILE__, __LINE__, logging::LOG_ERROR , ##__VA_ARGS__)
214#define COMPACT_GOOGLE_LOG_EX_ERROR_REPORT(ClassName, ...) \
215 logging::ClassName(__FILE__, __LINE__, \
216 logging::LOG_ERROR_REPORT , ##__VA_ARGS__)
217#define COMPACT_GOOGLE_LOG_EX_FATAL(ClassName, ...) \
218 logging::ClassName(__FILE__, __LINE__, logging::LOG_FATAL , ##__VA_ARGS__)
219#define COMPACT_GOOGLE_LOG_EX_DFATAL(ClassName, ...) \
220 logging::ClassName(__FILE__, __LINE__, \
221 logging::LOG_DFATAL_LEVEL , ##__VA_ARGS__)
222
initial.commitd7cae122008-07-26 21:49:38223#define COMPACT_GOOGLE_LOG_INFO \
[email protected]d8617a62009-10-09 23:52:20224 COMPACT_GOOGLE_LOG_EX_INFO(LogMessage)
initial.commitd7cae122008-07-26 21:49:38225#define COMPACT_GOOGLE_LOG_WARNING \
[email protected]d8617a62009-10-09 23:52:20226 COMPACT_GOOGLE_LOG_EX_WARNING(LogMessage)
initial.commitd7cae122008-07-26 21:49:38227#define COMPACT_GOOGLE_LOG_ERROR \
[email protected]d8617a62009-10-09 23:52:20228 COMPACT_GOOGLE_LOG_EX_ERROR(LogMessage)
[email protected]fb62a532009-02-12 01:19:05229#define COMPACT_GOOGLE_LOG_ERROR_REPORT \
[email protected]d8617a62009-10-09 23:52:20230 COMPACT_GOOGLE_LOG_EX_ERROR_REPORT(LogMessage)
initial.commitd7cae122008-07-26 21:49:38231#define COMPACT_GOOGLE_LOG_FATAL \
[email protected]d8617a62009-10-09 23:52:20232 COMPACT_GOOGLE_LOG_EX_FATAL(LogMessage)
initial.commitd7cae122008-07-26 21:49:38233#define COMPACT_GOOGLE_LOG_DFATAL \
[email protected]d8617a62009-10-09 23:52:20234 COMPACT_GOOGLE_LOG_EX_DFATAL(LogMessage)
initial.commitd7cae122008-07-26 21:49:38235
236// wingdi.h defines ERROR to be 0. When we call LOG(ERROR), it gets
237// substituted with 0, and it expands to COMPACT_GOOGLE_LOG_0. To allow us
238// to keep using this syntax, we define this macro to do the same thing
239// as COMPACT_GOOGLE_LOG_ERROR, and also define ERROR the same way that
240// the Windows SDK does for consistency.
241#define ERROR 0
[email protected]d8617a62009-10-09 23:52:20242#define COMPACT_GOOGLE_LOG_EX_0(ClassName, ...) \
243 COMPACT_GOOGLE_LOG_EX_ERROR(ClassName , ##__VA_ARGS__)
244#define COMPACT_GOOGLE_LOG_0 COMPACT_GOOGLE_LOG_ERROR
initial.commitd7cae122008-07-26 21:49:38245
246// We use the preprocessor's merging operator, "##", so that, e.g.,
247// LOG(INFO) becomes the token COMPACT_GOOGLE_LOG_INFO. There's some funny
248// subtle difference between ostream member streaming functions (e.g.,
249// ostream::operator<<(int) and ostream non-member streaming functions
250// (e.g., ::operator<<(ostream&, string&): it turns out that it's
251// impossible to stream something like a string directly to an unnamed
252// ostream. We employ a neat hack by calling the stream() member
253// function of LogMessage which seems to avoid the problem.
254
255#define LOG(severity) COMPACT_GOOGLE_LOG_ ## severity.stream()
256#define SYSLOG(severity) LOG(severity)
257
258#define LOG_IF(severity, condition) \
259 !(condition) ? (void) 0 : logging::LogMessageVoidify() & LOG(severity)
260#define SYSLOG_IF(severity, condition) LOG_IF(severity, condition)
261
262#define LOG_ASSERT(condition) \
263 LOG_IF(FATAL, !(condition)) << "Assert failed: " #condition ". "
264#define SYSLOG_ASSERT(condition) \
265 SYSLOG_IF(FATAL, !(condition)) << "Assert failed: " #condition ". "
266
[email protected]d8617a62009-10-09 23:52:20267#if defined(OS_WIN)
268#define LOG_GETLASTERROR(severity) \
269 COMPACT_GOOGLE_LOG_EX_ ## severity(Win32ErrorLogMessage, \
270 ::logging::GetLastSystemErrorCode()).stream()
271#define LOG_GETLASTERROR_MODULE(severity, module) \
272 COMPACT_GOOGLE_LOG_EX_ ## severity(Win32ErrorLogMessage, \
273 ::logging::GetLastSystemErrorCode(), module).stream()
274// PLOG is the usual error logging macro for each platform.
275#define PLOG(severity) LOG_GETLASTERROR(severity)
276#define DPLOG(severity) DLOG_GETLASTERROR(severity)
277#elif defined(OS_POSIX)
278#define LOG_ERRNO(severity) \
279 COMPACT_GOOGLE_LOG_EX_ ## severity(ErrnoLogMessage, \
280 ::logging::GetLastSystemErrorCode()).stream()
281// PLOG is the usual error logging macro for each platform.
282#define PLOG(severity) LOG_ERRNO(severity)
283#define DPLOG(severity) DLOG_ERRNO(severity)
284// TODO(tschmelcher): Should we add OSStatus logging for Mac?
285#endif
286
287#define PLOG_IF(severity, condition) \
288 !(condition) ? (void) 0 : logging::LogMessageVoidify() & PLOG(severity)
289
initial.commitd7cae122008-07-26 21:49:38290// CHECK dies with a fatal error if condition is not true. It is *not*
291// controlled by NDEBUG, so the check will be executed regardless of
292// compilation mode.
293#define CHECK(condition) \
294 LOG_IF(FATAL, !(condition)) << "Check failed: " #condition ". "
295
[email protected]d8617a62009-10-09 23:52:20296#define PCHECK(condition) \
297 PLOG_IF(FATAL, !(condition)) << "Check failed: " #condition ". "
298
initial.commitd7cae122008-07-26 21:49:38299// A container for a string pointer which can be evaluated to a bool -
300// true iff the pointer is NULL.
301struct CheckOpString {
302 CheckOpString(std::string* str) : str_(str) { }
303 // No destructor: if str_ is non-NULL, we're about to LOG(FATAL),
304 // so there's no point in cleaning up str_.
305 operator bool() const { return str_ != NULL; }
306 std::string* str_;
307};
308
309// Build the error message string. This is separate from the "Impl"
310// function template because it is not performance critical and so can
311// be out of line, while the "Impl" code should be inline.
312template<class t1, class t2>
313std::string* MakeCheckOpString(const t1& v1, const t2& v2, const char* names) {
314 std::ostringstream ss;
315 ss << names << " (" << v1 << " vs. " << v2 << ")";
316 std::string* msg = new std::string(ss.str());
317 return msg;
318}
319
320extern std::string* MakeCheckOpStringIntInt(int v1, int v2, const char* names);
321
322template<int, int>
[email protected]d3216442009-03-05 21:07:27323std::string* MakeCheckOpString(const int& v1,
324 const int& v2,
325 const char* names) {
initial.commitd7cae122008-07-26 21:49:38326 return MakeCheckOpStringIntInt(v1, v2, names);
327}
328
[email protected]e150c0382010-03-02 00:41:12329// Helper macro for binary operators.
330// Don't use this macro directly in your code, use CHECK_EQ et al below.
331#define CHECK_OP(name, op, val1, val2) \
332 if (logging::CheckOpString _result = \
333 logging::Check##name##Impl((val1), (val2), #val1 " " #op " " #val2)) \
334 logging::LogMessage(__FILE__, __LINE__, _result).stream()
335
336// Helper functions for string comparisons.
337// To avoid bloat, the definitions are in logging.cc.
338#define DECLARE_CHECK_STROP_IMPL(func, expected) \
339 std::string* Check##func##expected##Impl(const char* s1, \
340 const char* s2, \
341 const char* names);
342DECLARE_CHECK_STROP_IMPL(strcmp, true)
343DECLARE_CHECK_STROP_IMPL(strcmp, false)
344DECLARE_CHECK_STROP_IMPL(_stricmp, true)
345DECLARE_CHECK_STROP_IMPL(_stricmp, false)
346#undef DECLARE_CHECK_STROP_IMPL
347
348// Helper macro for string comparisons.
349// Don't use this macro directly in your code, use CHECK_STREQ et al below.
350#define CHECK_STROP(func, op, expected, s1, s2) \
351 while (CheckOpString _result = \
352 logging::Check##func##expected##Impl((s1), (s2), \
353 #s1 " " #op " " #s2)) \
354 LOG(FATAL) << *_result.str_
355
356// String (char*) equality/inequality checks.
357// CASE versions are case-insensitive.
358//
359// Note that "s1" and "s2" may be temporary strings which are destroyed
360// by the compiler at the end of the current "full expression"
361// (e.g. CHECK_STREQ(Foo().c_str(), Bar().c_str())).
362
363#define CHECK_STREQ(s1, s2) CHECK_STROP(strcmp, ==, true, s1, s2)
364#define CHECK_STRNE(s1, s2) CHECK_STROP(strcmp, !=, false, s1, s2)
365#define CHECK_STRCASEEQ(s1, s2) CHECK_STROP(_stricmp, ==, true, s1, s2)
366#define CHECK_STRCASENE(s1, s2) CHECK_STROP(_stricmp, !=, false, s1, s2)
367
368#define CHECK_INDEX(I,A) CHECK(I < (sizeof(A)/sizeof(A[0])))
369#define CHECK_BOUND(B,A) CHECK(B <= (sizeof(A)/sizeof(A[0])))
370
371#define CHECK_EQ(val1, val2) CHECK_OP(EQ, ==, val1, val2)
372#define CHECK_NE(val1, val2) CHECK_OP(NE, !=, val1, val2)
373#define CHECK_LE(val1, val2) CHECK_OP(LE, <=, val1, val2)
374#define CHECK_LT(val1, val2) CHECK_OP(LT, < , val1, val2)
375#define CHECK_GE(val1, val2) CHECK_OP(GE, >=, val1, val2)
376#define CHECK_GT(val1, val2) CHECK_OP(GT, > , val1, val2)
377
initial.commitd7cae122008-07-26 21:49:38378// Plus some debug-logging macros that get compiled to nothing for production
379//
380// DEBUG_MODE is for uses like
381// if (DEBUG_MODE) foo.CheckThatFoo();
382// instead of
383// #ifndef NDEBUG
384// foo.CheckThatFoo();
385// #endif
386
[email protected]e3cca332009-08-20 01:20:29387// http://crbug.com/16512 is open for a real fix for this. For now, Windows
388// uses OFFICIAL_BUILD and other platforms use the branding flag when NDEBUG is
389// defined.
390#if ( defined(OS_WIN) && defined(OFFICIAL_BUILD)) || \
391 (!defined(OS_WIN) && defined(NDEBUG) && defined(GOOGLE_CHROME_BUILD))
392// In order to have optimized code for official builds, remove DLOGs and
393// DCHECKs.
394#define OMIT_DLOG_AND_DCHECK 1
395#endif
396
397#ifdef OMIT_DLOG_AND_DCHECK
[email protected]94558e632008-12-11 22:10:17398
399#define DLOG(severity) \
400 true ? (void) 0 : logging::LogMessageVoidify() & LOG(severity)
401
402#define DLOG_IF(severity, condition) \
403 true ? (void) 0 : logging::LogMessageVoidify() & LOG(severity)
404
405#define DLOG_ASSERT(condition) \
406 true ? (void) 0 : LOG_ASSERT(condition)
407
[email protected]d8617a62009-10-09 23:52:20408#if defined(OS_WIN)
409#define DLOG_GETLASTERROR(severity) \
410 true ? (void) 0 : logging::LogMessageVoidify() & LOG_GETLASTERROR(severity)
411#define DLOG_GETLASTERROR_MODULE(severity, module) \
412 true ? (void) 0 : logging::LogMessageVoidify() & \
413 LOG_GETLASTERROR_MODULE(severity, module)
414#elif defined(OS_POSIX)
415#define DLOG_ERRNO(severity) \
416 true ? (void) 0 : logging::LogMessageVoidify() & LOG_ERRNO(severity)
417#endif
418
419#define DPLOG_IF(severity, condition) \
420 true ? (void) 0 : logging::LogMessageVoidify() & PLOG(severity)
421
[email protected]94558e632008-12-11 22:10:17422enum { DEBUG_MODE = 0 };
423
424// This macro can be followed by a sequence of stream parameters in
425// non-debug mode. The DCHECK and friends macros use this so that
426// the expanded expression DCHECK(foo) << "asdf" is still syntactically
427// valid, even though the expression will get optimized away.
[email protected]8c1766b92009-01-26 16:34:49428// In order to avoid variable unused warnings for code that only uses a
429// variable in a CHECK, we make sure to use the macro arguments.
[email protected]94558e632008-12-11 22:10:17430#define NDEBUG_EAT_STREAM_PARAMETERS \
431 logging::LogMessage(__FILE__, __LINE__).stream()
432
433#define DCHECK(condition) \
[email protected]8c1766b92009-01-26 16:34:49434 while (false && (condition)) NDEBUG_EAT_STREAM_PARAMETERS
[email protected]94558e632008-12-11 22:10:17435
[email protected]d8617a62009-10-09 23:52:20436#define DPCHECK(condition) \
437 while (false && (condition)) NDEBUG_EAT_STREAM_PARAMETERS
438
[email protected]94558e632008-12-11 22:10:17439#define DCHECK_EQ(val1, val2) \
[email protected]8c1766b92009-01-26 16:34:49440 while (false && (val1) == (val2)) NDEBUG_EAT_STREAM_PARAMETERS
[email protected]94558e632008-12-11 22:10:17441
442#define DCHECK_NE(val1, val2) \
[email protected]8c1766b92009-01-26 16:34:49443 while (false && (val1) == (val2)) NDEBUG_EAT_STREAM_PARAMETERS
[email protected]94558e632008-12-11 22:10:17444
445#define DCHECK_LE(val1, val2) \
[email protected]8c1766b92009-01-26 16:34:49446 while (false && (val1) == (val2)) NDEBUG_EAT_STREAM_PARAMETERS
[email protected]94558e632008-12-11 22:10:17447
448#define DCHECK_LT(val1, val2) \
[email protected]8c1766b92009-01-26 16:34:49449 while (false && (val1) == (val2)) NDEBUG_EAT_STREAM_PARAMETERS
[email protected]94558e632008-12-11 22:10:17450
451#define DCHECK_GE(val1, val2) \
[email protected]8c1766b92009-01-26 16:34:49452 while (false && (val1) == (val2)) NDEBUG_EAT_STREAM_PARAMETERS
[email protected]94558e632008-12-11 22:10:17453
454#define DCHECK_GT(val1, val2) \
[email protected]8c1766b92009-01-26 16:34:49455 while (false && (val1) == (val2)) NDEBUG_EAT_STREAM_PARAMETERS
[email protected]94558e632008-12-11 22:10:17456
457#define DCHECK_STREQ(str1, str2) \
[email protected]8c1766b92009-01-26 16:34:49458 while (false && (str1) == (str2)) NDEBUG_EAT_STREAM_PARAMETERS
[email protected]94558e632008-12-11 22:10:17459
460#define DCHECK_STRCASEEQ(str1, str2) \
[email protected]8c1766b92009-01-26 16:34:49461 while (false && (str1) == (str2)) NDEBUG_EAT_STREAM_PARAMETERS
[email protected]94558e632008-12-11 22:10:17462
463#define DCHECK_STRNE(str1, str2) \
[email protected]8c1766b92009-01-26 16:34:49464 while (false && (str1) == (str2)) NDEBUG_EAT_STREAM_PARAMETERS
[email protected]94558e632008-12-11 22:10:17465
466#define DCHECK_STRCASENE(str1, str2) \
[email protected]8c1766b92009-01-26 16:34:49467 while (false && (str1) == (str2)) NDEBUG_EAT_STREAM_PARAMETERS
[email protected]94558e632008-12-11 22:10:17468
[email protected]e3cca332009-08-20 01:20:29469#else // OMIT_DLOG_AND_DCHECK
470
initial.commitd7cae122008-07-26 21:49:38471#ifndef NDEBUG
[email protected]94558e632008-12-11 22:10:17472// On a regular debug build, we want to have DCHECKS and DLOGS enabled.
initial.commitd7cae122008-07-26 21:49:38473
474#define DLOG(severity) LOG(severity)
475#define DLOG_IF(severity, condition) LOG_IF(severity, condition)
476#define DLOG_ASSERT(condition) LOG_ASSERT(condition)
477
[email protected]d8617a62009-10-09 23:52:20478#if defined(OS_WIN)
479#define DLOG_GETLASTERROR(severity) LOG_GETLASTERROR(severity)
480#define DLOG_GETLASTERROR_MODULE(severity, module) \
481 LOG_GETLASTERROR_MODULE(severity, module)
482#elif defined(OS_POSIX)
483#define DLOG_ERRNO(severity) LOG_ERRNO(severity)
484#endif
485
486#define DPLOG_IF(severity, condition) PLOG_IF(severity, condition)
487
initial.commitd7cae122008-07-26 21:49:38488// debug-only checking. not executed in NDEBUG mode.
489enum { DEBUG_MODE = 1 };
[email protected]e150c0382010-03-02 00:41:12490#define DCHECK(condition) CHECK(condition)
491#define DPCHECK(condition) PCHECK(condition)
[email protected]d8617a62009-10-09 23:52:20492
initial.commitd7cae122008-07-26 21:49:38493// Helper macro for binary operators.
494// Don't use this macro directly in your code, use DCHECK_EQ et al below.
495#define DCHECK_OP(name, op, val1, val2) \
496 if (logging::CheckOpString _result = \
497 logging::Check##name##Impl((val1), (val2), #val1 " " #op " " #val2)) \
498 logging::LogMessage(__FILE__, __LINE__, _result).stream()
499
initial.commitd7cae122008-07-26 21:49:38500// Helper macro for string comparisons.
501// Don't use this macro directly in your code, use CHECK_STREQ et al below.
502#define DCHECK_STROP(func, op, expected, s1, s2) \
503 while (CheckOpString _result = \
504 logging::Check##func##expected##Impl((s1), (s2), \
505 #s1 " " #op " " #s2)) \
506 LOG(FATAL) << *_result.str_
507
508// String (char*) equality/inequality checks.
509// CASE versions are case-insensitive.
510//
511// Note that "s1" and "s2" may be temporary strings which are destroyed
512// by the compiler at the end of the current "full expression"
513// (e.g. DCHECK_STREQ(Foo().c_str(), Bar().c_str())).
514
515#define DCHECK_STREQ(s1, s2) DCHECK_STROP(strcmp, ==, true, s1, s2)
516#define DCHECK_STRNE(s1, s2) DCHECK_STROP(strcmp, !=, false, s1, s2)
517#define DCHECK_STRCASEEQ(s1, s2) DCHECK_STROP(_stricmp, ==, true, s1, s2)
518#define DCHECK_STRCASENE(s1, s2) DCHECK_STROP(_stricmp, !=, false, s1, s2)
519
520#define DCHECK_INDEX(I,A) DCHECK(I < (sizeof(A)/sizeof(A[0])))
521#define DCHECK_BOUND(B,A) DCHECK(B <= (sizeof(A)/sizeof(A[0])))
522
523#else // NDEBUG
[email protected]94558e632008-12-11 22:10:17524// On a regular release build we want to be able to enable DCHECKS through the
525// command line.
initial.commitd7cae122008-07-26 21:49:38526#define DLOG(severity) \
527 true ? (void) 0 : logging::LogMessageVoidify() & LOG(severity)
528
529#define DLOG_IF(severity, condition) \
530 true ? (void) 0 : logging::LogMessageVoidify() & LOG(severity)
531
532#define DLOG_ASSERT(condition) \
533 true ? (void) 0 : LOG_ASSERT(condition)
534
[email protected]d8617a62009-10-09 23:52:20535#if defined(OS_WIN)
536#define DLOG_GETLASTERROR(severity) \
537 true ? (void) 0 : logging::LogMessageVoidify() & LOG_GETLASTERROR(severity)
538#define DLOG_GETLASTERROR_MODULE(severity, module) \
539 true ? (void) 0 : logging::LogMessageVoidify() & \
540 LOG_GETLASTERROR_MODULE(severity, module)
541#elif defined(OS_POSIX)
542#define DLOG_ERRNO(severity) \
543 true ? (void) 0 : logging::LogMessageVoidify() & LOG_ERRNO(severity)
544#endif
545
546#define DPLOG_IF(severity, condition) \
547 true ? (void) 0 : logging::LogMessageVoidify() & PLOG(severity)
548
initial.commitd7cae122008-07-26 21:49:38549enum { DEBUG_MODE = 0 };
550
551// This macro can be followed by a sequence of stream parameters in
552// non-debug mode. The DCHECK and friends macros use this so that
553// the expanded expression DCHECK(foo) << "asdf" is still syntactically
554// valid, even though the expression will get optimized away.
555#define NDEBUG_EAT_STREAM_PARAMETERS \
556 logging::LogMessage(__FILE__, __LINE__).stream()
557
558// Set to true in InitLogging when we want to enable the dchecks in release.
559extern bool g_enable_dcheck;
560#define DCHECK(condition) \
561 !logging::g_enable_dcheck ? void (0) : \
[email protected]fb62a532009-02-12 01:19:05562 LOG_IF(ERROR_REPORT, !(condition)) << "Check failed: " #condition ". "
initial.commitd7cae122008-07-26 21:49:38563
[email protected]d8617a62009-10-09 23:52:20564#define DPCHECK(condition) \
565 !logging::g_enable_dcheck ? void (0) : \
566 PLOG_IF(ERROR_REPORT, !(condition)) << "Check failed: " #condition ". "
567
initial.commitd7cae122008-07-26 21:49:38568// Helper macro for binary operators.
569// Don't use this macro directly in your code, use DCHECK_EQ et al below.
570#define DCHECK_OP(name, op, val1, val2) \
571 if (logging::g_enable_dcheck) \
572 if (logging::CheckOpString _result = \
573 logging::Check##name##Impl((val1), (val2), #val1 " " #op " " #val2)) \
[email protected]fb62a532009-02-12 01:19:05574 logging::LogMessage(__FILE__, __LINE__, logging::LOG_ERROR_REPORT, \
575 _result).stream()
initial.commitd7cae122008-07-26 21:49:38576
577#define DCHECK_STREQ(str1, str2) \
578 while (false) NDEBUG_EAT_STREAM_PARAMETERS
579
580#define DCHECK_STRCASEEQ(str1, str2) \
581 while (false) NDEBUG_EAT_STREAM_PARAMETERS
582
583#define DCHECK_STRNE(str1, str2) \
584 while (false) NDEBUG_EAT_STREAM_PARAMETERS
585
586#define DCHECK_STRCASENE(str1, str2) \
587 while (false) NDEBUG_EAT_STREAM_PARAMETERS
588
589#endif // NDEBUG
590
initial.commitd7cae122008-07-26 21:49:38591// Equality/Inequality checks - compare two values, and log a LOG_FATAL message
592// including the two values when the result is not as expected. The values
593// must have operator<<(ostream, ...) defined.
594//
595// You may append to the error message like so:
596// DCHECK_NE(1, 2) << ": The world must be ending!";
597//
598// We are very careful to ensure that each argument is evaluated exactly
599// once, and that anything which is legal to pass as a function argument is
600// legal here. In particular, the arguments may be temporary expressions
601// which will end up being destroyed at the end of the apparent statement,
602// for example:
603// DCHECK_EQ(string("abc")[1], 'b');
604//
605// WARNING: These may not compile correctly if one of the arguments is a pointer
606// and the other is NULL. To work around this, simply static_cast NULL to the
607// type of the desired pointer.
608
609#define DCHECK_EQ(val1, val2) DCHECK_OP(EQ, ==, val1, val2)
610#define DCHECK_NE(val1, val2) DCHECK_OP(NE, !=, val1, val2)
611#define DCHECK_LE(val1, val2) DCHECK_OP(LE, <=, val1, val2)
612#define DCHECK_LT(val1, val2) DCHECK_OP(LT, < , val1, val2)
613#define DCHECK_GE(val1, val2) DCHECK_OP(GE, >=, val1, val2)
614#define DCHECK_GT(val1, val2) DCHECK_OP(GT, > , val1, val2)
615
[email protected]e3cca332009-08-20 01:20:29616#endif // OMIT_DLOG_AND_DCHECK
617#undef OMIT_DLOG_AND_DCHECK
initial.commitd7cae122008-07-26 21:49:38618
[email protected]e150c0382010-03-02 00:41:12619
620// Helper functions for CHECK_OP macro.
621// The (int, int) specialization works around the issue that the compiler
622// will not instantiate the template version of the function on values of
623// unnamed enum type - see comment below.
624#define DEFINE_CHECK_OP_IMPL(name, op) \
625 template <class t1, class t2> \
626 inline std::string* Check##name##Impl(const t1& v1, const t2& v2, \
627 const char* names) { \
628 if (v1 op v2) return NULL; \
629 else return MakeCheckOpString(v1, v2, names); \
630 } \
631 inline std::string* Check##name##Impl(int v1, int v2, const char* names) { \
632 if (v1 op v2) return NULL; \
633 else return MakeCheckOpString(v1, v2, names); \
634 }
635DEFINE_CHECK_OP_IMPL(EQ, ==)
636DEFINE_CHECK_OP_IMPL(NE, !=)
637DEFINE_CHECK_OP_IMPL(LE, <=)
638DEFINE_CHECK_OP_IMPL(LT, < )
639DEFINE_CHECK_OP_IMPL(GE, >=)
640DEFINE_CHECK_OP_IMPL(GT, > )
641#undef DEFINE_CHECK_OP_IMPL
642
initial.commitd7cae122008-07-26 21:49:38643#define NOTREACHED() DCHECK(false)
644
645// Redefine the standard assert to use our nice log files
646#undef assert
647#define assert(x) DLOG_ASSERT(x)
648
649// This class more or less represents a particular log message. You
650// create an instance of LogMessage and then stream stuff to it.
651// When you finish streaming to it, ~LogMessage is called and the
652// full message gets streamed to the appropriate destination.
653//
654// You shouldn't actually use LogMessage's constructor to log things,
655// though. You should use the LOG() macro (and variants thereof)
656// above.
657class LogMessage {
658 public:
659 LogMessage(const char* file, int line, LogSeverity severity, int ctr);
660
661 // Two special constructors that generate reduced amounts of code at
662 // LOG call sites for common cases.
663 //
664 // Used for LOG(INFO): Implied are:
665 // severity = LOG_INFO, ctr = 0
666 //
667 // Using this constructor instead of the more complex constructor above
668 // saves a couple of bytes per call site.
669 LogMessage(const char* file, int line);
670
671 // Used for LOG(severity) where severity != INFO. Implied
672 // are: ctr = 0
673 //
674 // Using this constructor instead of the more complex constructor above
675 // saves a couple of bytes per call site.
676 LogMessage(const char* file, int line, LogSeverity severity);
677
678 // A special constructor used for check failures.
679 // Implied severity = LOG_FATAL
680 LogMessage(const char* file, int line, const CheckOpString& result);
681
[email protected]fb62a532009-02-12 01:19:05682 // A special constructor used for check failures, with the option to
683 // specify severity.
684 LogMessage(const char* file, int line, LogSeverity severity,
685 const CheckOpString& result);
686
initial.commitd7cae122008-07-26 21:49:38687 ~LogMessage();
688
689 std::ostream& stream() { return stream_; }
690
691 private:
692 void Init(const char* file, int line);
693
694 LogSeverity severity_;
695 std::ostringstream stream_;
[email protected]c88873922008-07-30 13:02:03696 size_t message_start_; // Offset of the start of the message (past prefix
697 // info).
[email protected]3f85caa2009-04-14 16:52:11698#if defined(OS_WIN)
699 // Stores the current value of GetLastError in the constructor and restores
700 // it in the destructor by calling SetLastError.
701 // This is useful since the LogMessage class uses a lot of Win32 calls
702 // that will lose the value of GLE and the code that called the log function
703 // will have lost the thread error value when the log call returns.
704 class SaveLastError {
705 public:
706 SaveLastError();
707 ~SaveLastError();
708
709 unsigned long get_error() const { return last_error_; }
710
711 protected:
712 unsigned long last_error_;
713 };
714
715 SaveLastError last_error_;
716#endif
initial.commitd7cae122008-07-26 21:49:38717
[email protected]39be4242008-08-07 18:31:40718 DISALLOW_COPY_AND_ASSIGN(LogMessage);
initial.commitd7cae122008-07-26 21:49:38719};
720
721// A non-macro interface to the log facility; (useful
722// when the logging level is not a compile-time constant).
723inline void LogAtLevel(int const log_level, std::string const &msg) {
724 LogMessage(__FILE__, __LINE__, log_level).stream() << msg;
725}
726
727// This class is used to explicitly ignore values in the conditional
728// logging macros. This avoids compiler warnings like "value computed
729// is not used" and "statement has no effect".
730class LogMessageVoidify {
731 public:
732 LogMessageVoidify() { }
733 // This has to be an operator with a precedence lower than << but
734 // higher than ?:
735 void operator&(std::ostream&) { }
736};
737
[email protected]d8617a62009-10-09 23:52:20738#if defined(OS_WIN)
739typedef unsigned long SystemErrorCode;
740#elif defined(OS_POSIX)
741typedef int SystemErrorCode;
742#endif
743
744// Alias for ::GetLastError() on Windows and errno on POSIX. Avoids having to
745// pull in windows.h just for GetLastError() and DWORD.
746SystemErrorCode GetLastSystemErrorCode();
747
748#if defined(OS_WIN)
749// Appends a formatted system message of the GetLastError() type.
750class Win32ErrorLogMessage {
751 public:
752 Win32ErrorLogMessage(const char* file,
753 int line,
754 LogSeverity severity,
755 SystemErrorCode err,
756 const char* module);
757
758 Win32ErrorLogMessage(const char* file,
759 int line,
760 LogSeverity severity,
761 SystemErrorCode err);
762
763 std::ostream& stream() { return log_message_.stream(); }
764
765 // Appends the error message before destructing the encapsulated class.
766 ~Win32ErrorLogMessage();
767
768 private:
769 SystemErrorCode err_;
770 // Optional name of the module defining the error.
771 const char* module_;
772 LogMessage log_message_;
773
774 DISALLOW_COPY_AND_ASSIGN(Win32ErrorLogMessage);
775};
776#elif defined(OS_POSIX)
777// Appends a formatted system message of the errno type
778class ErrnoLogMessage {
779 public:
780 ErrnoLogMessage(const char* file,
781 int line,
782 LogSeverity severity,
783 SystemErrorCode err);
784
785 std::ostream& stream() { return log_message_.stream(); }
786
787 // Appends the error message before destructing the encapsulated class.
788 ~ErrnoLogMessage();
789
790 private:
791 SystemErrorCode err_;
792 LogMessage log_message_;
793
794 DISALLOW_COPY_AND_ASSIGN(ErrnoLogMessage);
795};
796#endif // OS_WIN
797
initial.commitd7cae122008-07-26 21:49:38798// Closes the log file explicitly if open.
799// NOTE: Since the log file is opened as necessary by the action of logging
800// statements, there's no guarantee that it will stay closed
801// after this call.
802void CloseLogFile();
803
[email protected]e36ddc82009-12-08 04:22:50804// Async signal safe logging mechanism.
805void RawLog(int level, const char* message);
806
807#define RAW_LOG(level, message) logging::RawLog(logging::LOG_ ## level, message)
808
809#define RAW_CHECK(condition) \
810 do { \
811 if (!(condition)) \
812 logging::RawLog(logging::LOG_FATAL, "Check failed: " #condition "\n"); \
813 } while (0)
814
[email protected]39be4242008-08-07 18:31:40815} // namespace logging
initial.commitd7cae122008-07-26 21:49:38816
[email protected]46ce5b562010-06-16 18:39:53817// These functions are provided as a convenience for logging, which is where we
818// use streams (it is against Google style to use streams in other places). It
819// is designed to allow you to emit non-ASCII Unicode strings to the log file,
820// which is normally ASCII. It is relatively slow, so try not to use it for
821// common cases. Non-ASCII characters will be converted to UTF-8 by these
822// operators.
823std::ostream& operator<<(std::ostream& out, const wchar_t* wstr);
824inline std::ostream& operator<<(std::ostream& out, const std::wstring& wstr) {
825 return out << wstr.c_str();
826}
827
[email protected]0dfc81b2008-08-25 03:44:40828// The NOTIMPLEMENTED() macro annotates codepaths which have
829// not been implemented yet.
830//
831// The implementation of this macro is controlled by NOTIMPLEMENTED_POLICY:
832// 0 -- Do nothing (stripped by compiler)
833// 1 -- Warn at compile time
834// 2 -- Fail at compile time
835// 3 -- Fail at runtime (DCHECK)
836// 4 -- [default] LOG(ERROR) at runtime
837// 5 -- LOG(ERROR) at runtime, only once per call-site
838
839#ifndef NOTIMPLEMENTED_POLICY
840// Select default policy: LOG(ERROR)
841#define NOTIMPLEMENTED_POLICY 4
842#endif
843
[email protected]f6cda752008-10-30 23:54:26844#if defined(COMPILER_GCC)
845// On Linux, with GCC, we can use __PRETTY_FUNCTION__ to get the demangled name
846// of the current function in the NOTIMPLEMENTED message.
847#define NOTIMPLEMENTED_MSG "Not implemented reached in " << __PRETTY_FUNCTION__
848#else
849#define NOTIMPLEMENTED_MSG "NOT IMPLEMENTED"
850#endif
851
[email protected]0dfc81b2008-08-25 03:44:40852#if NOTIMPLEMENTED_POLICY == 0
853#define NOTIMPLEMENTED() ;
854#elif NOTIMPLEMENTED_POLICY == 1
855// TODO, figure out how to generate a warning
856#define NOTIMPLEMENTED() COMPILE_ASSERT(false, NOT_IMPLEMENTED)
857#elif NOTIMPLEMENTED_POLICY == 2
858#define NOTIMPLEMENTED() COMPILE_ASSERT(false, NOT_IMPLEMENTED)
859#elif NOTIMPLEMENTED_POLICY == 3
860#define NOTIMPLEMENTED() NOTREACHED()
861#elif NOTIMPLEMENTED_POLICY == 4
[email protected]f6cda752008-10-30 23:54:26862#define NOTIMPLEMENTED() LOG(ERROR) << NOTIMPLEMENTED_MSG
[email protected]0dfc81b2008-08-25 03:44:40863#elif NOTIMPLEMENTED_POLICY == 5
864#define NOTIMPLEMENTED() do {\
865 static int count = 0;\
[email protected]f6cda752008-10-30 23:54:26866 LOG_IF(ERROR, 0 == count++) << NOTIMPLEMENTED_MSG;\
[email protected]0dfc81b2008-08-25 03:44:40867} while(0)
868#endif
869
[email protected]39be4242008-08-07 18:31:40870#endif // BASE_LOGGING_H_