blob: 2084739faa0ca177608d908b7b69edbdcb53c90d [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
[email protected]ff3d0c32010-08-23 19:57:46129// TODO(avi): do we want to do a unification of character types here?
130#if defined(OS_WIN)
131typedef wchar_t PathChar;
132#else
133typedef char PathChar;
134#endif
135
136// Define different names for the BaseInitLoggingImpl() function depending on
137// whether NDEBUG is defined or not so that we'll fail to link if someone tries
138// to compile logging.cc with NDEBUG but includes logging.h without defining it,
139// or vice versa.
140#if NDEBUG
141#define BaseInitLoggingImpl BaseInitLoggingImpl_built_with_NDEBUG
142#else
143#define BaseInitLoggingImpl BaseInitLoggingImpl_built_without_NDEBUG
144#endif
145
146// Implementation of the InitLogging() method declared below. We use a
147// more-specific name so we can #define it above without affecting other code
148// that has named stuff "InitLogging".
149void BaseInitLoggingImpl(const PathChar* log_file,
150 LoggingDestination logging_dest,
151 LogLockingState lock_log,
152 OldFileDeletionState delete_old);
153
initial.commitd7cae122008-07-26 21:49:38154// Sets the log file name and other global logging state. Calling this function
155// is recommended, and is normally done at the beginning of application init.
156// If you don't call it, all the flags will be initialized to their default
157// values, and there is a race condition that may leak a critical section
158// object if two threads try to do the first log at the same time.
159// See the definition of the enums above for descriptions and default values.
160//
161// The default log file is initialized to "debug.log" in the application
162// directory. You probably don't want this, especially since the program
163// directory may not be writable on an enduser's system.
[email protected]ff3d0c32010-08-23 19:57:46164inline void InitLogging(const PathChar* log_file,
165 LoggingDestination logging_dest,
166 LogLockingState lock_log,
167 OldFileDeletionState delete_old) {
168 BaseInitLoggingImpl(log_file, logging_dest, lock_log, delete_old);
169}
initial.commitd7cae122008-07-26 21:49:38170
171// Sets the log level. Anything at or above this level will be written to the
172// log file/displayed to the user (if applicable). Anything below this level
173// will be silently ignored. The log level defaults to 0 (everything is logged)
174// if this function is not called.
175void SetMinLogLevel(int level);
176
[email protected]8a2986ca2009-04-10 19:13:42177// Gets the current log level.
initial.commitd7cae122008-07-26 21:49:38178int GetMinLogLevel();
179
180// Sets the log filter prefix. Any log message below LOG_ERROR severity that
181// doesn't start with this prefix with be silently ignored. The filter defaults
182// to NULL (everything is logged) if this function is not called. Messages
183// with severity of LOG_ERROR or higher will not be filtered.
184void SetLogFilterPrefix(const char* filter);
185
186// Sets the common items you want to be prepended to each log message.
187// process and thread IDs default to off, the timestamp defaults to on.
188// If this function is not called, logging defaults to writing the timestamp
189// only.
190void SetLogItems(bool enable_process_id, bool enable_thread_id,
191 bool enable_timestamp, bool enable_tickcount);
192
[email protected]81e0a852010-08-17 00:38:12193// Sets whether or not you'd like to see fatal debug messages popped up in
194// a dialog box or not.
195// Dialogs are not shown by default.
196void SetShowErrorDialogs(bool enable_dialogs);
197
initial.commitd7cae122008-07-26 21:49:38198// Sets the Log Assert Handler that will be used to notify of check failures.
[email protected]fb62a532009-02-12 01:19:05199// The default handler shows a dialog box and then terminate the process,
200// however clients can use this function to override with their own handling
201// (e.g. a silent one for Unit Tests)
initial.commitd7cae122008-07-26 21:49:38202typedef void (*LogAssertHandlerFunction)(const std::string& str);
203void SetLogAssertHandler(LogAssertHandlerFunction handler);
[email protected]fb62a532009-02-12 01:19:05204// Sets the Log Report Handler that will be used to notify of check failures
205// in non-debug mode. The default handler shows a dialog box and continues
206// the execution, however clients can use this function to override with their
207// own handling.
208typedef void (*LogReportHandlerFunction)(const std::string& str);
209void SetLogReportHandler(LogReportHandlerFunction handler);
initial.commitd7cae122008-07-26 21:49:38210
[email protected]2b07b8412009-11-25 15:26:34211// Sets the Log Message Handler that gets passed every log message before
212// it's sent to other log destinations (if any).
213// Returns true to signal that it handled the message and the message
214// should not be sent to other log destinations.
215typedef bool (*LogMessageHandlerFunction)(int severity, const std::string& str);
216void SetLogMessageHandler(LogMessageHandlerFunction handler);
217
initial.commitd7cae122008-07-26 21:49:38218typedef int LogSeverity;
219const LogSeverity LOG_INFO = 0;
220const LogSeverity LOG_WARNING = 1;
221const LogSeverity LOG_ERROR = 2;
[email protected]fb62a532009-02-12 01:19:05222const LogSeverity LOG_ERROR_REPORT = 3;
223const LogSeverity LOG_FATAL = 4;
224const LogSeverity LOG_NUM_SEVERITIES = 5;
initial.commitd7cae122008-07-26 21:49:38225
[email protected]081bd4c2010-06-24 01:01:04226// LOG_DFATAL_LEVEL is LOG_FATAL in debug mode, ERROR in normal mode
initial.commitd7cae122008-07-26 21:49:38227#ifdef NDEBUG
[email protected]081bd4c2010-06-24 01:01:04228const LogSeverity LOG_DFATAL_LEVEL = LOG_ERROR;
initial.commitd7cae122008-07-26 21:49:38229#else
230const LogSeverity LOG_DFATAL_LEVEL = LOG_FATAL;
231#endif
232
233// A few definitions of macros that don't generate much code. These are used
234// by LOG() and LOG_IF, etc. Since these are used all over our code, it's
235// better to have compact code for these operations.
[email protected]d8617a62009-10-09 23:52:20236#define COMPACT_GOOGLE_LOG_EX_INFO(ClassName, ...) \
237 logging::ClassName(__FILE__, __LINE__, logging::LOG_INFO , ##__VA_ARGS__)
238#define COMPACT_GOOGLE_LOG_EX_WARNING(ClassName, ...) \
239 logging::ClassName(__FILE__, __LINE__, logging::LOG_WARNING , ##__VA_ARGS__)
240#define COMPACT_GOOGLE_LOG_EX_ERROR(ClassName, ...) \
241 logging::ClassName(__FILE__, __LINE__, logging::LOG_ERROR , ##__VA_ARGS__)
242#define COMPACT_GOOGLE_LOG_EX_ERROR_REPORT(ClassName, ...) \
243 logging::ClassName(__FILE__, __LINE__, \
244 logging::LOG_ERROR_REPORT , ##__VA_ARGS__)
245#define COMPACT_GOOGLE_LOG_EX_FATAL(ClassName, ...) \
246 logging::ClassName(__FILE__, __LINE__, logging::LOG_FATAL , ##__VA_ARGS__)
247#define COMPACT_GOOGLE_LOG_EX_DFATAL(ClassName, ...) \
248 logging::ClassName(__FILE__, __LINE__, \
249 logging::LOG_DFATAL_LEVEL , ##__VA_ARGS__)
250
initial.commitd7cae122008-07-26 21:49:38251#define COMPACT_GOOGLE_LOG_INFO \
[email protected]d8617a62009-10-09 23:52:20252 COMPACT_GOOGLE_LOG_EX_INFO(LogMessage)
initial.commitd7cae122008-07-26 21:49:38253#define COMPACT_GOOGLE_LOG_WARNING \
[email protected]d8617a62009-10-09 23:52:20254 COMPACT_GOOGLE_LOG_EX_WARNING(LogMessage)
initial.commitd7cae122008-07-26 21:49:38255#define COMPACT_GOOGLE_LOG_ERROR \
[email protected]d8617a62009-10-09 23:52:20256 COMPACT_GOOGLE_LOG_EX_ERROR(LogMessage)
[email protected]fb62a532009-02-12 01:19:05257#define COMPACT_GOOGLE_LOG_ERROR_REPORT \
[email protected]d8617a62009-10-09 23:52:20258 COMPACT_GOOGLE_LOG_EX_ERROR_REPORT(LogMessage)
initial.commitd7cae122008-07-26 21:49:38259#define COMPACT_GOOGLE_LOG_FATAL \
[email protected]d8617a62009-10-09 23:52:20260 COMPACT_GOOGLE_LOG_EX_FATAL(LogMessage)
initial.commitd7cae122008-07-26 21:49:38261#define COMPACT_GOOGLE_LOG_DFATAL \
[email protected]d8617a62009-10-09 23:52:20262 COMPACT_GOOGLE_LOG_EX_DFATAL(LogMessage)
initial.commitd7cae122008-07-26 21:49:38263
264// wingdi.h defines ERROR to be 0. When we call LOG(ERROR), it gets
265// substituted with 0, and it expands to COMPACT_GOOGLE_LOG_0. To allow us
266// to keep using this syntax, we define this macro to do the same thing
267// as COMPACT_GOOGLE_LOG_ERROR, and also define ERROR the same way that
268// the Windows SDK does for consistency.
269#define ERROR 0
[email protected]d8617a62009-10-09 23:52:20270#define COMPACT_GOOGLE_LOG_EX_0(ClassName, ...) \
271 COMPACT_GOOGLE_LOG_EX_ERROR(ClassName , ##__VA_ARGS__)
272#define COMPACT_GOOGLE_LOG_0 COMPACT_GOOGLE_LOG_ERROR
initial.commitd7cae122008-07-26 21:49:38273
274// We use the preprocessor's merging operator, "##", so that, e.g.,
275// LOG(INFO) becomes the token COMPACT_GOOGLE_LOG_INFO. There's some funny
276// subtle difference between ostream member streaming functions (e.g.,
277// ostream::operator<<(int) and ostream non-member streaming functions
278// (e.g., ::operator<<(ostream&, string&): it turns out that it's
279// impossible to stream something like a string directly to an unnamed
280// ostream. We employ a neat hack by calling the stream() member
281// function of LogMessage which seems to avoid the problem.
282
283#define LOG(severity) COMPACT_GOOGLE_LOG_ ## severity.stream()
284#define SYSLOG(severity) LOG(severity)
285
286#define LOG_IF(severity, condition) \
287 !(condition) ? (void) 0 : logging::LogMessageVoidify() & LOG(severity)
288#define SYSLOG_IF(severity, condition) LOG_IF(severity, condition)
289
290#define LOG_ASSERT(condition) \
291 LOG_IF(FATAL, !(condition)) << "Assert failed: " #condition ". "
292#define SYSLOG_ASSERT(condition) \
293 SYSLOG_IF(FATAL, !(condition)) << "Assert failed: " #condition ". "
294
[email protected]d8617a62009-10-09 23:52:20295#if defined(OS_WIN)
296#define LOG_GETLASTERROR(severity) \
297 COMPACT_GOOGLE_LOG_EX_ ## severity(Win32ErrorLogMessage, \
298 ::logging::GetLastSystemErrorCode()).stream()
299#define LOG_GETLASTERROR_MODULE(severity, module) \
300 COMPACT_GOOGLE_LOG_EX_ ## severity(Win32ErrorLogMessage, \
301 ::logging::GetLastSystemErrorCode(), module).stream()
302// PLOG is the usual error logging macro for each platform.
303#define PLOG(severity) LOG_GETLASTERROR(severity)
304#define DPLOG(severity) DLOG_GETLASTERROR(severity)
305#elif defined(OS_POSIX)
306#define LOG_ERRNO(severity) \
307 COMPACT_GOOGLE_LOG_EX_ ## severity(ErrnoLogMessage, \
308 ::logging::GetLastSystemErrorCode()).stream()
309// PLOG is the usual error logging macro for each platform.
310#define PLOG(severity) LOG_ERRNO(severity)
311#define DPLOG(severity) DLOG_ERRNO(severity)
312// TODO(tschmelcher): Should we add OSStatus logging for Mac?
313#endif
314
315#define PLOG_IF(severity, condition) \
316 !(condition) ? (void) 0 : logging::LogMessageVoidify() & PLOG(severity)
317
initial.commitd7cae122008-07-26 21:49:38318// CHECK dies with a fatal error if condition is not true. It is *not*
319// controlled by NDEBUG, so the check will be executed regardless of
320// compilation mode.
321#define CHECK(condition) \
322 LOG_IF(FATAL, !(condition)) << "Check failed: " #condition ". "
323
[email protected]d8617a62009-10-09 23:52:20324#define PCHECK(condition) \
325 PLOG_IF(FATAL, !(condition)) << "Check failed: " #condition ". "
326
initial.commitd7cae122008-07-26 21:49:38327// A container for a string pointer which can be evaluated to a bool -
328// true iff the pointer is NULL.
329struct CheckOpString {
330 CheckOpString(std::string* str) : str_(str) { }
331 // No destructor: if str_ is non-NULL, we're about to LOG(FATAL),
332 // so there's no point in cleaning up str_.
333 operator bool() const { return str_ != NULL; }
334 std::string* str_;
335};
336
337// Build the error message string. This is separate from the "Impl"
338// function template because it is not performance critical and so can
339// be out of line, while the "Impl" code should be inline.
340template<class t1, class t2>
341std::string* MakeCheckOpString(const t1& v1, const t2& v2, const char* names) {
342 std::ostringstream ss;
343 ss << names << " (" << v1 << " vs. " << v2 << ")";
344 std::string* msg = new std::string(ss.str());
345 return msg;
346}
347
348extern std::string* MakeCheckOpStringIntInt(int v1, int v2, const char* names);
349
350template<int, int>
[email protected]d3216442009-03-05 21:07:27351std::string* MakeCheckOpString(const int& v1,
352 const int& v2,
353 const char* names) {
initial.commitd7cae122008-07-26 21:49:38354 return MakeCheckOpStringIntInt(v1, v2, names);
355}
356
[email protected]e150c0382010-03-02 00:41:12357// Helper macro for binary operators.
358// Don't use this macro directly in your code, use CHECK_EQ et al below.
359#define CHECK_OP(name, op, val1, val2) \
360 if (logging::CheckOpString _result = \
361 logging::Check##name##Impl((val1), (val2), #val1 " " #op " " #val2)) \
362 logging::LogMessage(__FILE__, __LINE__, _result).stream()
363
364// Helper functions for string comparisons.
365// To avoid bloat, the definitions are in logging.cc.
366#define DECLARE_CHECK_STROP_IMPL(func, expected) \
367 std::string* Check##func##expected##Impl(const char* s1, \
368 const char* s2, \
369 const char* names);
370DECLARE_CHECK_STROP_IMPL(strcmp, true)
371DECLARE_CHECK_STROP_IMPL(strcmp, false)
372DECLARE_CHECK_STROP_IMPL(_stricmp, true)
373DECLARE_CHECK_STROP_IMPL(_stricmp, false)
374#undef DECLARE_CHECK_STROP_IMPL
375
376// Helper macro for string comparisons.
377// Don't use this macro directly in your code, use CHECK_STREQ et al below.
378#define CHECK_STROP(func, op, expected, s1, s2) \
379 while (CheckOpString _result = \
380 logging::Check##func##expected##Impl((s1), (s2), \
381 #s1 " " #op " " #s2)) \
382 LOG(FATAL) << *_result.str_
383
384// String (char*) equality/inequality checks.
385// CASE versions are case-insensitive.
386//
387// Note that "s1" and "s2" may be temporary strings which are destroyed
388// by the compiler at the end of the current "full expression"
389// (e.g. CHECK_STREQ(Foo().c_str(), Bar().c_str())).
390
391#define CHECK_STREQ(s1, s2) CHECK_STROP(strcmp, ==, true, s1, s2)
392#define CHECK_STRNE(s1, s2) CHECK_STROP(strcmp, !=, false, s1, s2)
393#define CHECK_STRCASEEQ(s1, s2) CHECK_STROP(_stricmp, ==, true, s1, s2)
394#define CHECK_STRCASENE(s1, s2) CHECK_STROP(_stricmp, !=, false, s1, s2)
395
396#define CHECK_INDEX(I,A) CHECK(I < (sizeof(A)/sizeof(A[0])))
397#define CHECK_BOUND(B,A) CHECK(B <= (sizeof(A)/sizeof(A[0])))
398
399#define CHECK_EQ(val1, val2) CHECK_OP(EQ, ==, val1, val2)
400#define CHECK_NE(val1, val2) CHECK_OP(NE, !=, val1, val2)
401#define CHECK_LE(val1, val2) CHECK_OP(LE, <=, val1, val2)
402#define CHECK_LT(val1, val2) CHECK_OP(LT, < , val1, val2)
403#define CHECK_GE(val1, val2) CHECK_OP(GE, >=, val1, val2)
404#define CHECK_GT(val1, val2) CHECK_OP(GT, > , val1, val2)
405
initial.commitd7cae122008-07-26 21:49:38406// Plus some debug-logging macros that get compiled to nothing for production
407//
408// DEBUG_MODE is for uses like
409// if (DEBUG_MODE) foo.CheckThatFoo();
410// instead of
411// #ifndef NDEBUG
412// foo.CheckThatFoo();
413// #endif
414
[email protected]e3cca332009-08-20 01:20:29415// http://crbug.com/16512 is open for a real fix for this. For now, Windows
416// uses OFFICIAL_BUILD and other platforms use the branding flag when NDEBUG is
417// defined.
418#if ( defined(OS_WIN) && defined(OFFICIAL_BUILD)) || \
419 (!defined(OS_WIN) && defined(NDEBUG) && defined(GOOGLE_CHROME_BUILD))
420// In order to have optimized code for official builds, remove DLOGs and
421// DCHECKs.
422#define OMIT_DLOG_AND_DCHECK 1
423#endif
424
425#ifdef OMIT_DLOG_AND_DCHECK
[email protected]94558e632008-12-11 22:10:17426
427#define DLOG(severity) \
428 true ? (void) 0 : logging::LogMessageVoidify() & LOG(severity)
429
430#define DLOG_IF(severity, condition) \
431 true ? (void) 0 : logging::LogMessageVoidify() & LOG(severity)
432
433#define DLOG_ASSERT(condition) \
434 true ? (void) 0 : LOG_ASSERT(condition)
435
[email protected]d8617a62009-10-09 23:52:20436#if defined(OS_WIN)
437#define DLOG_GETLASTERROR(severity) \
438 true ? (void) 0 : logging::LogMessageVoidify() & LOG_GETLASTERROR(severity)
439#define DLOG_GETLASTERROR_MODULE(severity, module) \
440 true ? (void) 0 : logging::LogMessageVoidify() & \
441 LOG_GETLASTERROR_MODULE(severity, module)
442#elif defined(OS_POSIX)
443#define DLOG_ERRNO(severity) \
444 true ? (void) 0 : logging::LogMessageVoidify() & LOG_ERRNO(severity)
445#endif
446
447#define DPLOG_IF(severity, condition) \
448 true ? (void) 0 : logging::LogMessageVoidify() & PLOG(severity)
449
[email protected]94558e632008-12-11 22:10:17450enum { DEBUG_MODE = 0 };
451
452// This macro can be followed by a sequence of stream parameters in
453// non-debug mode. The DCHECK and friends macros use this so that
454// the expanded expression DCHECK(foo) << "asdf" is still syntactically
455// valid, even though the expression will get optimized away.
[email protected]8c1766b92009-01-26 16:34:49456// In order to avoid variable unused warnings for code that only uses a
457// variable in a CHECK, we make sure to use the macro arguments.
[email protected]94558e632008-12-11 22:10:17458#define NDEBUG_EAT_STREAM_PARAMETERS \
459 logging::LogMessage(__FILE__, __LINE__).stream()
460
461#define DCHECK(condition) \
[email protected]8c1766b92009-01-26 16:34:49462 while (false && (condition)) NDEBUG_EAT_STREAM_PARAMETERS
[email protected]94558e632008-12-11 22:10:17463
[email protected]d8617a62009-10-09 23:52:20464#define DPCHECK(condition) \
465 while (false && (condition)) NDEBUG_EAT_STREAM_PARAMETERS
466
[email protected]94558e632008-12-11 22:10:17467#define DCHECK_EQ(val1, val2) \
[email protected]8c1766b92009-01-26 16:34:49468 while (false && (val1) == (val2)) NDEBUG_EAT_STREAM_PARAMETERS
[email protected]94558e632008-12-11 22:10:17469
470#define DCHECK_NE(val1, val2) \
[email protected]8c1766b92009-01-26 16:34:49471 while (false && (val1) == (val2)) NDEBUG_EAT_STREAM_PARAMETERS
[email protected]94558e632008-12-11 22:10:17472
473#define DCHECK_LE(val1, val2) \
[email protected]8c1766b92009-01-26 16:34:49474 while (false && (val1) == (val2)) NDEBUG_EAT_STREAM_PARAMETERS
[email protected]94558e632008-12-11 22:10:17475
476#define DCHECK_LT(val1, val2) \
[email protected]8c1766b92009-01-26 16:34:49477 while (false && (val1) == (val2)) NDEBUG_EAT_STREAM_PARAMETERS
[email protected]94558e632008-12-11 22:10:17478
479#define DCHECK_GE(val1, val2) \
[email protected]8c1766b92009-01-26 16:34:49480 while (false && (val1) == (val2)) NDEBUG_EAT_STREAM_PARAMETERS
[email protected]94558e632008-12-11 22:10:17481
482#define DCHECK_GT(val1, val2) \
[email protected]8c1766b92009-01-26 16:34:49483 while (false && (val1) == (val2)) NDEBUG_EAT_STREAM_PARAMETERS
[email protected]94558e632008-12-11 22:10:17484
485#define DCHECK_STREQ(str1, str2) \
[email protected]8c1766b92009-01-26 16:34:49486 while (false && (str1) == (str2)) NDEBUG_EAT_STREAM_PARAMETERS
[email protected]94558e632008-12-11 22:10:17487
488#define DCHECK_STRCASEEQ(str1, str2) \
[email protected]8c1766b92009-01-26 16:34:49489 while (false && (str1) == (str2)) NDEBUG_EAT_STREAM_PARAMETERS
[email protected]94558e632008-12-11 22:10:17490
491#define DCHECK_STRNE(str1, str2) \
[email protected]8c1766b92009-01-26 16:34:49492 while (false && (str1) == (str2)) NDEBUG_EAT_STREAM_PARAMETERS
[email protected]94558e632008-12-11 22:10:17493
494#define DCHECK_STRCASENE(str1, str2) \
[email protected]8c1766b92009-01-26 16:34:49495 while (false && (str1) == (str2)) NDEBUG_EAT_STREAM_PARAMETERS
[email protected]94558e632008-12-11 22:10:17496
[email protected]e3cca332009-08-20 01:20:29497#else // OMIT_DLOG_AND_DCHECK
498
initial.commitd7cae122008-07-26 21:49:38499#ifndef NDEBUG
[email protected]94558e632008-12-11 22:10:17500// On a regular debug build, we want to have DCHECKS and DLOGS enabled.
initial.commitd7cae122008-07-26 21:49:38501
502#define DLOG(severity) LOG(severity)
503#define DLOG_IF(severity, condition) LOG_IF(severity, condition)
504#define DLOG_ASSERT(condition) LOG_ASSERT(condition)
505
[email protected]d8617a62009-10-09 23:52:20506#if defined(OS_WIN)
507#define DLOG_GETLASTERROR(severity) LOG_GETLASTERROR(severity)
508#define DLOG_GETLASTERROR_MODULE(severity, module) \
509 LOG_GETLASTERROR_MODULE(severity, module)
510#elif defined(OS_POSIX)
511#define DLOG_ERRNO(severity) LOG_ERRNO(severity)
512#endif
513
514#define DPLOG_IF(severity, condition) PLOG_IF(severity, condition)
515
initial.commitd7cae122008-07-26 21:49:38516// debug-only checking. not executed in NDEBUG mode.
517enum { DEBUG_MODE = 1 };
[email protected]e150c0382010-03-02 00:41:12518#define DCHECK(condition) CHECK(condition)
519#define DPCHECK(condition) PCHECK(condition)
[email protected]d8617a62009-10-09 23:52:20520
initial.commitd7cae122008-07-26 21:49:38521// Helper macro for binary operators.
522// Don't use this macro directly in your code, use DCHECK_EQ et al below.
523#define DCHECK_OP(name, op, val1, val2) \
524 if (logging::CheckOpString _result = \
525 logging::Check##name##Impl((val1), (val2), #val1 " " #op " " #val2)) \
526 logging::LogMessage(__FILE__, __LINE__, _result).stream()
527
initial.commitd7cae122008-07-26 21:49:38528// Helper macro for string comparisons.
529// Don't use this macro directly in your code, use CHECK_STREQ et al below.
530#define DCHECK_STROP(func, op, expected, s1, s2) \
531 while (CheckOpString _result = \
532 logging::Check##func##expected##Impl((s1), (s2), \
533 #s1 " " #op " " #s2)) \
534 LOG(FATAL) << *_result.str_
535
536// String (char*) equality/inequality checks.
537// CASE versions are case-insensitive.
538//
539// Note that "s1" and "s2" may be temporary strings which are destroyed
540// by the compiler at the end of the current "full expression"
541// (e.g. DCHECK_STREQ(Foo().c_str(), Bar().c_str())).
542
543#define DCHECK_STREQ(s1, s2) DCHECK_STROP(strcmp, ==, true, s1, s2)
544#define DCHECK_STRNE(s1, s2) DCHECK_STROP(strcmp, !=, false, s1, s2)
545#define DCHECK_STRCASEEQ(s1, s2) DCHECK_STROP(_stricmp, ==, true, s1, s2)
546#define DCHECK_STRCASENE(s1, s2) DCHECK_STROP(_stricmp, !=, false, s1, s2)
547
548#define DCHECK_INDEX(I,A) DCHECK(I < (sizeof(A)/sizeof(A[0])))
549#define DCHECK_BOUND(B,A) DCHECK(B <= (sizeof(A)/sizeof(A[0])))
550
551#else // NDEBUG
[email protected]94558e632008-12-11 22:10:17552// On a regular release build we want to be able to enable DCHECKS through the
553// command line.
initial.commitd7cae122008-07-26 21:49:38554#define DLOG(severity) \
555 true ? (void) 0 : logging::LogMessageVoidify() & LOG(severity)
556
557#define DLOG_IF(severity, condition) \
558 true ? (void) 0 : logging::LogMessageVoidify() & LOG(severity)
559
560#define DLOG_ASSERT(condition) \
561 true ? (void) 0 : LOG_ASSERT(condition)
562
[email protected]d8617a62009-10-09 23:52:20563#if defined(OS_WIN)
564#define DLOG_GETLASTERROR(severity) \
565 true ? (void) 0 : logging::LogMessageVoidify() & LOG_GETLASTERROR(severity)
566#define DLOG_GETLASTERROR_MODULE(severity, module) \
567 true ? (void) 0 : logging::LogMessageVoidify() & \
568 LOG_GETLASTERROR_MODULE(severity, module)
569#elif defined(OS_POSIX)
570#define DLOG_ERRNO(severity) \
571 true ? (void) 0 : logging::LogMessageVoidify() & LOG_ERRNO(severity)
572#endif
573
574#define DPLOG_IF(severity, condition) \
575 true ? (void) 0 : logging::LogMessageVoidify() & PLOG(severity)
576
initial.commitd7cae122008-07-26 21:49:38577enum { DEBUG_MODE = 0 };
578
579// This macro can be followed by a sequence of stream parameters in
580// non-debug mode. The DCHECK and friends macros use this so that
581// the expanded expression DCHECK(foo) << "asdf" is still syntactically
582// valid, even though the expression will get optimized away.
583#define NDEBUG_EAT_STREAM_PARAMETERS \
584 logging::LogMessage(__FILE__, __LINE__).stream()
585
586// Set to true in InitLogging when we want to enable the dchecks in release.
587extern bool g_enable_dcheck;
588#define DCHECK(condition) \
589 !logging::g_enable_dcheck ? void (0) : \
[email protected]fb62a532009-02-12 01:19:05590 LOG_IF(ERROR_REPORT, !(condition)) << "Check failed: " #condition ". "
initial.commitd7cae122008-07-26 21:49:38591
[email protected]d8617a62009-10-09 23:52:20592#define DPCHECK(condition) \
593 !logging::g_enable_dcheck ? void (0) : \
594 PLOG_IF(ERROR_REPORT, !(condition)) << "Check failed: " #condition ". "
595
initial.commitd7cae122008-07-26 21:49:38596// Helper macro for binary operators.
597// Don't use this macro directly in your code, use DCHECK_EQ et al below.
598#define DCHECK_OP(name, op, val1, val2) \
599 if (logging::g_enable_dcheck) \
600 if (logging::CheckOpString _result = \
601 logging::Check##name##Impl((val1), (val2), #val1 " " #op " " #val2)) \
[email protected]fb62a532009-02-12 01:19:05602 logging::LogMessage(__FILE__, __LINE__, logging::LOG_ERROR_REPORT, \
603 _result).stream()
initial.commitd7cae122008-07-26 21:49:38604
605#define DCHECK_STREQ(str1, str2) \
606 while (false) NDEBUG_EAT_STREAM_PARAMETERS
607
608#define DCHECK_STRCASEEQ(str1, str2) \
609 while (false) NDEBUG_EAT_STREAM_PARAMETERS
610
611#define DCHECK_STRNE(str1, str2) \
612 while (false) NDEBUG_EAT_STREAM_PARAMETERS
613
614#define DCHECK_STRCASENE(str1, str2) \
615 while (false) NDEBUG_EAT_STREAM_PARAMETERS
616
617#endif // NDEBUG
618
initial.commitd7cae122008-07-26 21:49:38619// Equality/Inequality checks - compare two values, and log a LOG_FATAL message
620// including the two values when the result is not as expected. The values
621// must have operator<<(ostream, ...) defined.
622//
623// You may append to the error message like so:
624// DCHECK_NE(1, 2) << ": The world must be ending!";
625//
626// We are very careful to ensure that each argument is evaluated exactly
627// once, and that anything which is legal to pass as a function argument is
628// legal here. In particular, the arguments may be temporary expressions
629// which will end up being destroyed at the end of the apparent statement,
630// for example:
631// DCHECK_EQ(string("abc")[1], 'b');
632//
633// WARNING: These may not compile correctly if one of the arguments is a pointer
634// and the other is NULL. To work around this, simply static_cast NULL to the
635// type of the desired pointer.
636
637#define DCHECK_EQ(val1, val2) DCHECK_OP(EQ, ==, val1, val2)
638#define DCHECK_NE(val1, val2) DCHECK_OP(NE, !=, val1, val2)
639#define DCHECK_LE(val1, val2) DCHECK_OP(LE, <=, val1, val2)
640#define DCHECK_LT(val1, val2) DCHECK_OP(LT, < , val1, val2)
641#define DCHECK_GE(val1, val2) DCHECK_OP(GE, >=, val1, val2)
642#define DCHECK_GT(val1, val2) DCHECK_OP(GT, > , val1, val2)
643
[email protected]e3cca332009-08-20 01:20:29644#endif // OMIT_DLOG_AND_DCHECK
645#undef OMIT_DLOG_AND_DCHECK
initial.commitd7cae122008-07-26 21:49:38646
[email protected]e150c0382010-03-02 00:41:12647
648// Helper functions for CHECK_OP macro.
649// The (int, int) specialization works around the issue that the compiler
650// will not instantiate the template version of the function on values of
651// unnamed enum type - see comment below.
652#define DEFINE_CHECK_OP_IMPL(name, op) \
653 template <class t1, class t2> \
654 inline std::string* Check##name##Impl(const t1& v1, const t2& v2, \
655 const char* names) { \
656 if (v1 op v2) return NULL; \
657 else return MakeCheckOpString(v1, v2, names); \
658 } \
659 inline std::string* Check##name##Impl(int v1, int v2, const char* names) { \
660 if (v1 op v2) return NULL; \
661 else return MakeCheckOpString(v1, v2, names); \
662 }
663DEFINE_CHECK_OP_IMPL(EQ, ==)
664DEFINE_CHECK_OP_IMPL(NE, !=)
665DEFINE_CHECK_OP_IMPL(LE, <=)
666DEFINE_CHECK_OP_IMPL(LT, < )
667DEFINE_CHECK_OP_IMPL(GE, >=)
668DEFINE_CHECK_OP_IMPL(GT, > )
669#undef DEFINE_CHECK_OP_IMPL
670
initial.commitd7cae122008-07-26 21:49:38671#define NOTREACHED() DCHECK(false)
672
673// Redefine the standard assert to use our nice log files
674#undef assert
675#define assert(x) DLOG_ASSERT(x)
676
677// This class more or less represents a particular log message. You
678// create an instance of LogMessage and then stream stuff to it.
679// When you finish streaming to it, ~LogMessage is called and the
680// full message gets streamed to the appropriate destination.
681//
682// You shouldn't actually use LogMessage's constructor to log things,
683// though. You should use the LOG() macro (and variants thereof)
684// above.
685class LogMessage {
686 public:
687 LogMessage(const char* file, int line, LogSeverity severity, int ctr);
688
689 // Two special constructors that generate reduced amounts of code at
690 // LOG call sites for common cases.
691 //
692 // Used for LOG(INFO): Implied are:
693 // severity = LOG_INFO, ctr = 0
694 //
695 // Using this constructor instead of the more complex constructor above
696 // saves a couple of bytes per call site.
697 LogMessage(const char* file, int line);
698
699 // Used for LOG(severity) where severity != INFO. Implied
700 // are: ctr = 0
701 //
702 // Using this constructor instead of the more complex constructor above
703 // saves a couple of bytes per call site.
704 LogMessage(const char* file, int line, LogSeverity severity);
705
706 // A special constructor used for check failures.
707 // Implied severity = LOG_FATAL
708 LogMessage(const char* file, int line, const CheckOpString& result);
709
[email protected]fb62a532009-02-12 01:19:05710 // A special constructor used for check failures, with the option to
711 // specify severity.
712 LogMessage(const char* file, int line, LogSeverity severity,
713 const CheckOpString& result);
714
initial.commitd7cae122008-07-26 21:49:38715 ~LogMessage();
716
717 std::ostream& stream() { return stream_; }
718
719 private:
720 void Init(const char* file, int line);
721
722 LogSeverity severity_;
723 std::ostringstream stream_;
[email protected]c88873922008-07-30 13:02:03724 size_t message_start_; // Offset of the start of the message (past prefix
725 // info).
[email protected]3f85caa2009-04-14 16:52:11726#if defined(OS_WIN)
727 // Stores the current value of GetLastError in the constructor and restores
728 // it in the destructor by calling SetLastError.
729 // This is useful since the LogMessage class uses a lot of Win32 calls
730 // that will lose the value of GLE and the code that called the log function
731 // will have lost the thread error value when the log call returns.
732 class SaveLastError {
733 public:
734 SaveLastError();
735 ~SaveLastError();
736
737 unsigned long get_error() const { return last_error_; }
738
739 protected:
740 unsigned long last_error_;
741 };
742
743 SaveLastError last_error_;
744#endif
initial.commitd7cae122008-07-26 21:49:38745
[email protected]39be4242008-08-07 18:31:40746 DISALLOW_COPY_AND_ASSIGN(LogMessage);
initial.commitd7cae122008-07-26 21:49:38747};
748
749// A non-macro interface to the log facility; (useful
750// when the logging level is not a compile-time constant).
751inline void LogAtLevel(int const log_level, std::string const &msg) {
752 LogMessage(__FILE__, __LINE__, log_level).stream() << msg;
753}
754
755// This class is used to explicitly ignore values in the conditional
756// logging macros. This avoids compiler warnings like "value computed
757// is not used" and "statement has no effect".
758class LogMessageVoidify {
759 public:
760 LogMessageVoidify() { }
761 // This has to be an operator with a precedence lower than << but
762 // higher than ?:
763 void operator&(std::ostream&) { }
764};
765
[email protected]d8617a62009-10-09 23:52:20766#if defined(OS_WIN)
767typedef unsigned long SystemErrorCode;
768#elif defined(OS_POSIX)
769typedef int SystemErrorCode;
770#endif
771
772// Alias for ::GetLastError() on Windows and errno on POSIX. Avoids having to
773// pull in windows.h just for GetLastError() and DWORD.
774SystemErrorCode GetLastSystemErrorCode();
775
776#if defined(OS_WIN)
777// Appends a formatted system message of the GetLastError() type.
778class Win32ErrorLogMessage {
779 public:
780 Win32ErrorLogMessage(const char* file,
781 int line,
782 LogSeverity severity,
783 SystemErrorCode err,
784 const char* module);
785
786 Win32ErrorLogMessage(const char* file,
787 int line,
788 LogSeverity severity,
789 SystemErrorCode err);
790
791 std::ostream& stream() { return log_message_.stream(); }
792
793 // Appends the error message before destructing the encapsulated class.
794 ~Win32ErrorLogMessage();
795
796 private:
797 SystemErrorCode err_;
798 // Optional name of the module defining the error.
799 const char* module_;
800 LogMessage log_message_;
801
802 DISALLOW_COPY_AND_ASSIGN(Win32ErrorLogMessage);
803};
804#elif defined(OS_POSIX)
805// Appends a formatted system message of the errno type
806class ErrnoLogMessage {
807 public:
808 ErrnoLogMessage(const char* file,
809 int line,
810 LogSeverity severity,
811 SystemErrorCode err);
812
813 std::ostream& stream() { return log_message_.stream(); }
814
815 // Appends the error message before destructing the encapsulated class.
816 ~ErrnoLogMessage();
817
818 private:
819 SystemErrorCode err_;
820 LogMessage log_message_;
821
822 DISALLOW_COPY_AND_ASSIGN(ErrnoLogMessage);
823};
824#endif // OS_WIN
825
initial.commitd7cae122008-07-26 21:49:38826// Closes the log file explicitly if open.
827// NOTE: Since the log file is opened as necessary by the action of logging
828// statements, there's no guarantee that it will stay closed
829// after this call.
830void CloseLogFile();
831
[email protected]e36ddc82009-12-08 04:22:50832// Async signal safe logging mechanism.
833void RawLog(int level, const char* message);
834
835#define RAW_LOG(level, message) logging::RawLog(logging::LOG_ ## level, message)
836
837#define RAW_CHECK(condition) \
838 do { \
839 if (!(condition)) \
840 logging::RawLog(logging::LOG_FATAL, "Check failed: " #condition "\n"); \
841 } while (0)
842
[email protected]39be4242008-08-07 18:31:40843} // namespace logging
initial.commitd7cae122008-07-26 21:49:38844
[email protected]46ce5b562010-06-16 18:39:53845// These functions are provided as a convenience for logging, which is where we
846// use streams (it is against Google style to use streams in other places). It
847// is designed to allow you to emit non-ASCII Unicode strings to the log file,
848// which is normally ASCII. It is relatively slow, so try not to use it for
849// common cases. Non-ASCII characters will be converted to UTF-8 by these
850// operators.
851std::ostream& operator<<(std::ostream& out, const wchar_t* wstr);
852inline std::ostream& operator<<(std::ostream& out, const std::wstring& wstr) {
853 return out << wstr.c_str();
854}
855
[email protected]0dfc81b2008-08-25 03:44:40856// The NOTIMPLEMENTED() macro annotates codepaths which have
857// not been implemented yet.
858//
859// The implementation of this macro is controlled by NOTIMPLEMENTED_POLICY:
860// 0 -- Do nothing (stripped by compiler)
861// 1 -- Warn at compile time
862// 2 -- Fail at compile time
863// 3 -- Fail at runtime (DCHECK)
864// 4 -- [default] LOG(ERROR) at runtime
865// 5 -- LOG(ERROR) at runtime, only once per call-site
866
867#ifndef NOTIMPLEMENTED_POLICY
868// Select default policy: LOG(ERROR)
869#define NOTIMPLEMENTED_POLICY 4
870#endif
871
[email protected]f6cda752008-10-30 23:54:26872#if defined(COMPILER_GCC)
873// On Linux, with GCC, we can use __PRETTY_FUNCTION__ to get the demangled name
874// of the current function in the NOTIMPLEMENTED message.
875#define NOTIMPLEMENTED_MSG "Not implemented reached in " << __PRETTY_FUNCTION__
876#else
877#define NOTIMPLEMENTED_MSG "NOT IMPLEMENTED"
878#endif
879
[email protected]0dfc81b2008-08-25 03:44:40880#if NOTIMPLEMENTED_POLICY == 0
881#define NOTIMPLEMENTED() ;
882#elif NOTIMPLEMENTED_POLICY == 1
883// TODO, figure out how to generate a warning
884#define NOTIMPLEMENTED() COMPILE_ASSERT(false, NOT_IMPLEMENTED)
885#elif NOTIMPLEMENTED_POLICY == 2
886#define NOTIMPLEMENTED() COMPILE_ASSERT(false, NOT_IMPLEMENTED)
887#elif NOTIMPLEMENTED_POLICY == 3
888#define NOTIMPLEMENTED() NOTREACHED()
889#elif NOTIMPLEMENTED_POLICY == 4
[email protected]f6cda752008-10-30 23:54:26890#define NOTIMPLEMENTED() LOG(ERROR) << NOTIMPLEMENTED_MSG
[email protected]0dfc81b2008-08-25 03:44:40891#elif NOTIMPLEMENTED_POLICY == 5
892#define NOTIMPLEMENTED() do {\
893 static int count = 0;\
[email protected]f6cda752008-10-30 23:54:26894 LOG_IF(ERROR, 0 == count++) << NOTIMPLEMENTED_MSG;\
[email protected]0dfc81b2008-08-25 03:44:40895} while(0)
896#endif
897
[email protected]39be4242008-08-07 18:31:40898#endif // BASE_LOGGING_H_