blob: de8de7168696790826a6195ac6b2ecd5d17d00ef [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_
initial.commitd7cae122008-07-26 21:49:387
8#include <string>
9#include <cstring>
10#include <sstream>
11
12#include "base/basictypes.h"
initial.commitd7cae122008-07-26 21:49:3813
14//
15// Optional message capabilities
16// -----------------------------
17// Assertion failed messages and fatal errors are displayed in a dialog box
18// before the application exits. However, running this UI creates a message
19// loop, which causes application messages to be processed and potentially
20// dispatched to existing application windows. Since the application is in a
21// bad state when this assertion dialog is displayed, these messages may not
22// get processed and hang the dialog, or the application might go crazy.
23//
24// Therefore, it can be beneficial to display the error dialog in a separate
25// process from the main application. When the logging system needs to display
26// a fatal error dialog box, it will look for a program called
27// "DebugMessage.exe" in the same directory as the application executable. It
28// will run this application with the message as the command line, and will
29// not include the name of the application as is traditional for easier
30// parsing.
31//
32// The code for DebugMessage.exe is only one line. In WinMain, do:
33// MessageBox(NULL, GetCommandLineW(), L"Fatal Error", 0);
34//
35// If DebugMessage.exe is not found, the logging code will use a normal
36// MessageBox, potentially causing the problems discussed above.
37
38
39// Instructions
40// ------------
41//
42// Make a bunch of macros for logging. The way to log things is to stream
43// things to LOG(<a particular severity level>). E.g.,
44//
45// LOG(INFO) << "Found " << num_cookies << " cookies";
46//
47// You can also do conditional logging:
48//
49// LOG_IF(INFO, num_cookies > 10) << "Got lots of cookies";
50//
51// The above will cause log messages to be output on the 1st, 11th, 21st, ...
52// times it is executed. Note that the special COUNTER value is used to
53// identify which repetition is happening.
54//
55// The CHECK(condition) macro is active in both debug and release builds and
56// effectively performs a LOG(FATAL) which terminates the process and
57// generates a crashdump unless a debugger is attached.
58//
59// There are also "debug mode" logging macros like the ones above:
60//
61// DLOG(INFO) << "Found cookies";
62//
63// DLOG_IF(INFO, num_cookies > 10) << "Got lots of cookies";
64//
65// All "debug mode" logging is compiled away to nothing for non-debug mode
66// compiles. LOG_IF and development flags also work well together
67// because the code can be compiled away sometimes.
68//
69// We also have
70//
71// LOG_ASSERT(assertion);
72// DLOG_ASSERT(assertion);
73//
74// which is syntactic sugar for {,D}LOG_IF(FATAL, assert fails) << assertion;
75//
76// We also override the standard 'assert' to use 'DLOG_ASSERT'.
77//
[email protected]d8617a62009-10-09 23:52:2078// Lastly, there is:
79//
80// PLOG(ERROR) << "Couldn't do foo";
81// DPLOG(ERROR) << "Couldn't do foo";
82// PLOG_IF(ERROR, cond) << "Couldn't do foo";
83// DPLOG_IF(ERROR, cond) << "Couldn't do foo";
84// PCHECK(condition) << "Couldn't do foo";
85// DPCHECK(condition) << "Couldn't do foo";
86//
87// which append the last system error to the message in string form (taken from
88// GetLastError() on Windows and errno on POSIX).
89//
initial.commitd7cae122008-07-26 21:49:3890// The supported severity levels for macros that allow you to specify one
[email protected]fb62a532009-02-12 01:19:0591// are (in increasing order of severity) INFO, WARNING, ERROR, ERROR_REPORT,
92// and FATAL.
initial.commitd7cae122008-07-26 21:49:3893//
94// Very important: logging a message at the FATAL severity level causes
95// the program to terminate (after the message is logged).
[email protected]fb62a532009-02-12 01:19:0596//
97// Note the special severity of ERROR_REPORT only available/relevant in normal
98// mode, which displays error dialog without terminating the program. There is
99// no error dialog for severity ERROR or below in normal mode.
100//
101// There is also the special severity of DFATAL, which logs FATAL in
102// debug mode, ERROR_REPORT in normal mode.
initial.commitd7cae122008-07-26 21:49:38103
104namespace logging {
105
106// Where to record logging output? A flat file and/or system debug log via
[email protected]88aa41e82008-11-18 00:59:04107// OutputDebugString. Defaults on Windows to LOG_ONLY_TO_FILE, and on
108// POSIX to LOG_ONLY_TO_SYSTEM_DEBUG_LOG (aka stderr).
initial.commitd7cae122008-07-26 21:49:38109enum LoggingDestination { LOG_NONE,
110 LOG_ONLY_TO_FILE,
111 LOG_ONLY_TO_SYSTEM_DEBUG_LOG,
112 LOG_TO_BOTH_FILE_AND_SYSTEM_DEBUG_LOG };
113
114// Indicates that the log file should be locked when being written to.
115// Often, there is no locking, which is fine for a single threaded program.
116// If logging is being done from multiple threads or there can be more than
117// one process doing the logging, the file should be locked during writes to
118// make each log outut atomic. Other writers will block.
119//
120// All processes writing to the log file must have their locking set for it to
121// work properly. Defaults to DONT_LOCK_LOG_FILE.
122enum LogLockingState { LOCK_LOG_FILE, DONT_LOCK_LOG_FILE };
123
124// On startup, should we delete or append to an existing log file (if any)?
125// Defaults to APPEND_TO_OLD_LOG_FILE.
126enum OldFileDeletionState { DELETE_OLD_LOG_FILE, APPEND_TO_OLD_LOG_FILE };
127
128// Sets the log file name and other global logging state. Calling this function
129// is recommended, and is normally done at the beginning of application init.
130// If you don't call it, all the flags will be initialized to their default
131// values, and there is a race condition that may leak a critical section
132// object if two threads try to do the first log at the same time.
133// See the definition of the enums above for descriptions and default values.
134//
135// The default log file is initialized to "debug.log" in the application
136// directory. You probably don't want this, especially since the program
137// directory may not be writable on an enduser's system.
[email protected]39be4242008-08-07 18:31:40138#if defined(OS_WIN)
initial.commitd7cae122008-07-26 21:49:38139void InitLogging(const wchar_t* log_file, LoggingDestination logging_dest,
140 LogLockingState lock_log, OldFileDeletionState delete_old);
[email protected]39be4242008-08-07 18:31:40141#elif defined(OS_POSIX)
initial.commitd7cae122008-07-26 21:49:38142// TODO(avi): do we want to do a unification of character types here?
143void InitLogging(const char* log_file, LoggingDestination logging_dest,
144 LogLockingState lock_log, OldFileDeletionState delete_old);
145#endif
146
147// Sets the log level. Anything at or above this level will be written to the
148// log file/displayed to the user (if applicable). Anything below this level
149// will be silently ignored. The log level defaults to 0 (everything is logged)
150// if this function is not called.
151void SetMinLogLevel(int level);
152
[email protected]8a2986ca2009-04-10 19:13:42153// Gets the current log level.
initial.commitd7cae122008-07-26 21:49:38154int GetMinLogLevel();
155
[email protected]4883a4e2009-06-06 19:59:36156#if defined(OS_LINUX)
157// Get the file descriptor used for logging.
158// Returns -1 if none open.
159// Needed by ZygoteManager.
160int GetLoggingFileDescriptor();
161#endif
162
initial.commitd7cae122008-07-26 21:49:38163// Sets the log filter prefix. Any log message below LOG_ERROR severity that
164// doesn't start with this prefix with be silently ignored. The filter defaults
165// to NULL (everything is logged) if this function is not called. Messages
166// with severity of LOG_ERROR or higher will not be filtered.
167void SetLogFilterPrefix(const char* filter);
168
169// Sets the common items you want to be prepended to each log message.
170// process and thread IDs default to off, the timestamp defaults to on.
171// If this function is not called, logging defaults to writing the timestamp
172// only.
173void SetLogItems(bool enable_process_id, bool enable_thread_id,
174 bool enable_timestamp, bool enable_tickcount);
175
176// Sets the Log Assert Handler that will be used to notify of check failures.
[email protected]fb62a532009-02-12 01:19:05177// The default handler shows a dialog box and then terminate the process,
178// however clients can use this function to override with their own handling
179// (e.g. a silent one for Unit Tests)
initial.commitd7cae122008-07-26 21:49:38180typedef void (*LogAssertHandlerFunction)(const std::string& str);
181void SetLogAssertHandler(LogAssertHandlerFunction handler);
[email protected]fb62a532009-02-12 01:19:05182// Sets the Log Report Handler that will be used to notify of check failures
183// in non-debug mode. The default handler shows a dialog box and continues
184// the execution, however clients can use this function to override with their
185// own handling.
186typedef void (*LogReportHandlerFunction)(const std::string& str);
187void SetLogReportHandler(LogReportHandlerFunction handler);
initial.commitd7cae122008-07-26 21:49:38188
189typedef int LogSeverity;
190const LogSeverity LOG_INFO = 0;
191const LogSeverity LOG_WARNING = 1;
192const LogSeverity LOG_ERROR = 2;
[email protected]fb62a532009-02-12 01:19:05193const LogSeverity LOG_ERROR_REPORT = 3;
194const LogSeverity LOG_FATAL = 4;
195const LogSeverity LOG_NUM_SEVERITIES = 5;
initial.commitd7cae122008-07-26 21:49:38196
[email protected]fb62a532009-02-12 01:19:05197// LOG_DFATAL_LEVEL is LOG_FATAL in debug mode, ERROR_REPORT in normal mode
initial.commitd7cae122008-07-26 21:49:38198#ifdef NDEBUG
[email protected]fb62a532009-02-12 01:19:05199const LogSeverity LOG_DFATAL_LEVEL = LOG_ERROR_REPORT;
initial.commitd7cae122008-07-26 21:49:38200#else
201const LogSeverity LOG_DFATAL_LEVEL = LOG_FATAL;
202#endif
203
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.
[email protected]d8617a62009-10-09 23:52:20207#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__)
221
initial.commitd7cae122008-07-26 21:49:38222#define COMPACT_GOOGLE_LOG_INFO \
[email protected]d8617a62009-10-09 23:52:20223 COMPACT_GOOGLE_LOG_EX_INFO(LogMessage)
initial.commitd7cae122008-07-26 21:49:38224#define COMPACT_GOOGLE_LOG_WARNING \
[email protected]d8617a62009-10-09 23:52:20225 COMPACT_GOOGLE_LOG_EX_WARNING(LogMessage)
initial.commitd7cae122008-07-26 21:49:38226#define COMPACT_GOOGLE_LOG_ERROR \
[email protected]d8617a62009-10-09 23:52:20227 COMPACT_GOOGLE_LOG_EX_ERROR(LogMessage)
[email protected]fb62a532009-02-12 01:19:05228#define COMPACT_GOOGLE_LOG_ERROR_REPORT \
[email protected]d8617a62009-10-09 23:52:20229 COMPACT_GOOGLE_LOG_EX_ERROR_REPORT(LogMessage)
initial.commitd7cae122008-07-26 21:49:38230#define COMPACT_GOOGLE_LOG_FATAL \
[email protected]d8617a62009-10-09 23:52:20231 COMPACT_GOOGLE_LOG_EX_FATAL(LogMessage)
initial.commitd7cae122008-07-26 21:49:38232#define COMPACT_GOOGLE_LOG_DFATAL \
[email protected]d8617a62009-10-09 23:52:20233 COMPACT_GOOGLE_LOG_EX_DFATAL(LogMessage)
initial.commitd7cae122008-07-26 21:49:38234
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
[email protected]d8617a62009-10-09 23:52:20241#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
initial.commitd7cae122008-07-26 21:49:38244
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.
253
254#define LOG(severity) COMPACT_GOOGLE_LOG_ ## severity.stream()
255#define SYSLOG(severity) LOG(severity)
256
257#define LOG_IF(severity, condition) \
258 !(condition) ? (void) 0 : logging::LogMessageVoidify() & LOG(severity)
259#define SYSLOG_IF(severity, condition) LOG_IF(severity, condition)
260
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 ". "
265
[email protected]d8617a62009-10-09 23:52:20266#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
285
286#define PLOG_IF(severity, condition) \
287 !(condition) ? (void) 0 : logging::LogMessageVoidify() & PLOG(severity)
288
initial.commitd7cae122008-07-26 21:49:38289// 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 ". "
294
[email protected]d8617a62009-10-09 23:52:20295#define PCHECK(condition) \
296 PLOG_IF(FATAL, !(condition)) << "Check failed: " #condition ". "
297
initial.commitd7cae122008-07-26 21:49:38298// A container for a string pointer which can be evaluated to a bool -
299// true iff the pointer is NULL.
300struct 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_;
306};
307
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.
311template<class t1, class t2>
312std::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;
317}
318
319extern std::string* MakeCheckOpStringIntInt(int v1, int v2, const char* names);
320
321template<int, int>
[email protected]d3216442009-03-05 21:07:27322std::string* MakeCheckOpString(const int& v1,
323 const int& v2,
324 const char* names) {
initial.commitd7cae122008-07-26 21:49:38325 return MakeCheckOpStringIntInt(v1, v2, names);
326}
327
328// Plus some debug-logging macros that get compiled to nothing for production
329//
330// DEBUG_MODE is for uses like
331// if (DEBUG_MODE) foo.CheckThatFoo();
332// instead of
333// #ifndef NDEBUG
334// foo.CheckThatFoo();
335// #endif
336
[email protected]e3cca332009-08-20 01:20:29337// http://crbug.com/16512 is open for a real fix for this. For now, Windows
338// uses OFFICIAL_BUILD and other platforms use the branding flag when NDEBUG is
339// defined.
340#if ( defined(OS_WIN) && defined(OFFICIAL_BUILD)) || \
341 (!defined(OS_WIN) && defined(NDEBUG) && defined(GOOGLE_CHROME_BUILD))
342// In order to have optimized code for official builds, remove DLOGs and
343// DCHECKs.
344#define OMIT_DLOG_AND_DCHECK 1
345#endif
346
347#ifdef OMIT_DLOG_AND_DCHECK
[email protected]94558e632008-12-11 22:10:17348
349#define DLOG(severity) \
350 true ? (void) 0 : logging::LogMessageVoidify() & LOG(severity)
351
352#define DLOG_IF(severity, condition) \
353 true ? (void) 0 : logging::LogMessageVoidify() & LOG(severity)
354
355#define DLOG_ASSERT(condition) \
356 true ? (void) 0 : LOG_ASSERT(condition)
357
[email protected]d8617a62009-10-09 23:52:20358#if defined(OS_WIN)
359#define DLOG_GETLASTERROR(severity) \
360 true ? (void) 0 : logging::LogMessageVoidify() & LOG_GETLASTERROR(severity)
361#define DLOG_GETLASTERROR_MODULE(severity, module) \
362 true ? (void) 0 : logging::LogMessageVoidify() & \
363 LOG_GETLASTERROR_MODULE(severity, module)
364#elif defined(OS_POSIX)
365#define DLOG_ERRNO(severity) \
366 true ? (void) 0 : logging::LogMessageVoidify() & LOG_ERRNO(severity)
367#endif
368
369#define DPLOG_IF(severity, condition) \
370 true ? (void) 0 : logging::LogMessageVoidify() & PLOG(severity)
371
[email protected]94558e632008-12-11 22:10:17372enum { DEBUG_MODE = 0 };
373
374// This macro can be followed by a sequence of stream parameters in
375// non-debug mode. The DCHECK and friends macros use this so that
376// the expanded expression DCHECK(foo) << "asdf" is still syntactically
377// valid, even though the expression will get optimized away.
[email protected]8c1766b92009-01-26 16:34:49378// In order to avoid variable unused warnings for code that only uses a
379// variable in a CHECK, we make sure to use the macro arguments.
[email protected]94558e632008-12-11 22:10:17380#define NDEBUG_EAT_STREAM_PARAMETERS \
381 logging::LogMessage(__FILE__, __LINE__).stream()
382
383#define DCHECK(condition) \
[email protected]8c1766b92009-01-26 16:34:49384 while (false && (condition)) NDEBUG_EAT_STREAM_PARAMETERS
[email protected]94558e632008-12-11 22:10:17385
[email protected]d8617a62009-10-09 23:52:20386#define DPCHECK(condition) \
387 while (false && (condition)) NDEBUG_EAT_STREAM_PARAMETERS
388
[email protected]94558e632008-12-11 22:10:17389#define DCHECK_EQ(val1, val2) \
[email protected]8c1766b92009-01-26 16:34:49390 while (false && (val1) == (val2)) NDEBUG_EAT_STREAM_PARAMETERS
[email protected]94558e632008-12-11 22:10:17391
392#define DCHECK_NE(val1, val2) \
[email protected]8c1766b92009-01-26 16:34:49393 while (false && (val1) == (val2)) NDEBUG_EAT_STREAM_PARAMETERS
[email protected]94558e632008-12-11 22:10:17394
395#define DCHECK_LE(val1, val2) \
[email protected]8c1766b92009-01-26 16:34:49396 while (false && (val1) == (val2)) NDEBUG_EAT_STREAM_PARAMETERS
[email protected]94558e632008-12-11 22:10:17397
398#define DCHECK_LT(val1, val2) \
[email protected]8c1766b92009-01-26 16:34:49399 while (false && (val1) == (val2)) NDEBUG_EAT_STREAM_PARAMETERS
[email protected]94558e632008-12-11 22:10:17400
401#define DCHECK_GE(val1, val2) \
[email protected]8c1766b92009-01-26 16:34:49402 while (false && (val1) == (val2)) NDEBUG_EAT_STREAM_PARAMETERS
[email protected]94558e632008-12-11 22:10:17403
404#define DCHECK_GT(val1, val2) \
[email protected]8c1766b92009-01-26 16:34:49405 while (false && (val1) == (val2)) NDEBUG_EAT_STREAM_PARAMETERS
[email protected]94558e632008-12-11 22:10:17406
407#define DCHECK_STREQ(str1, str2) \
[email protected]8c1766b92009-01-26 16:34:49408 while (false && (str1) == (str2)) NDEBUG_EAT_STREAM_PARAMETERS
[email protected]94558e632008-12-11 22:10:17409
410#define DCHECK_STRCASEEQ(str1, str2) \
[email protected]8c1766b92009-01-26 16:34:49411 while (false && (str1) == (str2)) NDEBUG_EAT_STREAM_PARAMETERS
[email protected]94558e632008-12-11 22:10:17412
413#define DCHECK_STRNE(str1, str2) \
[email protected]8c1766b92009-01-26 16:34:49414 while (false && (str1) == (str2)) NDEBUG_EAT_STREAM_PARAMETERS
[email protected]94558e632008-12-11 22:10:17415
416#define DCHECK_STRCASENE(str1, str2) \
[email protected]8c1766b92009-01-26 16:34:49417 while (false && (str1) == (str2)) NDEBUG_EAT_STREAM_PARAMETERS
[email protected]94558e632008-12-11 22:10:17418
[email protected]e3cca332009-08-20 01:20:29419#else // OMIT_DLOG_AND_DCHECK
420
initial.commitd7cae122008-07-26 21:49:38421#ifndef NDEBUG
[email protected]94558e632008-12-11 22:10:17422// On a regular debug build, we want to have DCHECKS and DLOGS enabled.
initial.commitd7cae122008-07-26 21:49:38423
424#define DLOG(severity) LOG(severity)
425#define DLOG_IF(severity, condition) LOG_IF(severity, condition)
426#define DLOG_ASSERT(condition) LOG_ASSERT(condition)
427
[email protected]d8617a62009-10-09 23:52:20428#if defined(OS_WIN)
429#define DLOG_GETLASTERROR(severity) LOG_GETLASTERROR(severity)
430#define DLOG_GETLASTERROR_MODULE(severity, module) \
431 LOG_GETLASTERROR_MODULE(severity, module)
432#elif defined(OS_POSIX)
433#define DLOG_ERRNO(severity) LOG_ERRNO(severity)
434#endif
435
436#define DPLOG_IF(severity, condition) PLOG_IF(severity, condition)
437
initial.commitd7cae122008-07-26 21:49:38438// debug-only checking. not executed in NDEBUG mode.
439enum { DEBUG_MODE = 1 };
440#define DCHECK(condition) \
441 LOG_IF(FATAL, !(condition)) << "Check failed: " #condition ". "
442
[email protected]d8617a62009-10-09 23:52:20443#define DPCHECK(condition) \
444 PLOG_IF(FATAL, !(condition)) << "Check failed: " #condition ". "
445
initial.commitd7cae122008-07-26 21:49:38446// Helper macro for binary operators.
447// Don't use this macro directly in your code, use DCHECK_EQ et al below.
448#define DCHECK_OP(name, op, val1, val2) \
449 if (logging::CheckOpString _result = \
450 logging::Check##name##Impl((val1), (val2), #val1 " " #op " " #val2)) \
451 logging::LogMessage(__FILE__, __LINE__, _result).stream()
452
453// Helper functions for string comparisons.
454// To avoid bloat, the definitions are in logging.cc.
455#define DECLARE_DCHECK_STROP_IMPL(func, expected) \
456 std::string* Check##func##expected##Impl(const char* s1, \
457 const char* s2, \
458 const char* names);
459DECLARE_DCHECK_STROP_IMPL(strcmp, true)
460DECLARE_DCHECK_STROP_IMPL(strcmp, false)
461DECLARE_DCHECK_STROP_IMPL(_stricmp, true)
462DECLARE_DCHECK_STROP_IMPL(_stricmp, false)
463#undef DECLARE_DCHECK_STROP_IMPL
464
465// Helper macro for string comparisons.
466// Don't use this macro directly in your code, use CHECK_STREQ et al below.
467#define DCHECK_STROP(func, op, expected, s1, s2) \
468 while (CheckOpString _result = \
469 logging::Check##func##expected##Impl((s1), (s2), \
470 #s1 " " #op " " #s2)) \
471 LOG(FATAL) << *_result.str_
472
473// String (char*) equality/inequality checks.
474// CASE versions are case-insensitive.
475//
476// Note that "s1" and "s2" may be temporary strings which are destroyed
477// by the compiler at the end of the current "full expression"
478// (e.g. DCHECK_STREQ(Foo().c_str(), Bar().c_str())).
479
480#define DCHECK_STREQ(s1, s2) DCHECK_STROP(strcmp, ==, true, s1, s2)
481#define DCHECK_STRNE(s1, s2) DCHECK_STROP(strcmp, !=, false, s1, s2)
482#define DCHECK_STRCASEEQ(s1, s2) DCHECK_STROP(_stricmp, ==, true, s1, s2)
483#define DCHECK_STRCASENE(s1, s2) DCHECK_STROP(_stricmp, !=, false, s1, s2)
484
485#define DCHECK_INDEX(I,A) DCHECK(I < (sizeof(A)/sizeof(A[0])))
486#define DCHECK_BOUND(B,A) DCHECK(B <= (sizeof(A)/sizeof(A[0])))
487
488#else // NDEBUG
[email protected]94558e632008-12-11 22:10:17489// On a regular release build we want to be able to enable DCHECKS through the
490// command line.
initial.commitd7cae122008-07-26 21:49:38491#define DLOG(severity) \
492 true ? (void) 0 : logging::LogMessageVoidify() & LOG(severity)
493
494#define DLOG_IF(severity, condition) \
495 true ? (void) 0 : logging::LogMessageVoidify() & LOG(severity)
496
497#define DLOG_ASSERT(condition) \
498 true ? (void) 0 : LOG_ASSERT(condition)
499
[email protected]d8617a62009-10-09 23:52:20500#if defined(OS_WIN)
501#define DLOG_GETLASTERROR(severity) \
502 true ? (void) 0 : logging::LogMessageVoidify() & LOG_GETLASTERROR(severity)
503#define DLOG_GETLASTERROR_MODULE(severity, module) \
504 true ? (void) 0 : logging::LogMessageVoidify() & \
505 LOG_GETLASTERROR_MODULE(severity, module)
506#elif defined(OS_POSIX)
507#define DLOG_ERRNO(severity) \
508 true ? (void) 0 : logging::LogMessageVoidify() & LOG_ERRNO(severity)
509#endif
510
511#define DPLOG_IF(severity, condition) \
512 true ? (void) 0 : logging::LogMessageVoidify() & PLOG(severity)
513
initial.commitd7cae122008-07-26 21:49:38514enum { DEBUG_MODE = 0 };
515
516// This macro can be followed by a sequence of stream parameters in
517// non-debug mode. The DCHECK and friends macros use this so that
518// the expanded expression DCHECK(foo) << "asdf" is still syntactically
519// valid, even though the expression will get optimized away.
520#define NDEBUG_EAT_STREAM_PARAMETERS \
521 logging::LogMessage(__FILE__, __LINE__).stream()
522
523// Set to true in InitLogging when we want to enable the dchecks in release.
524extern bool g_enable_dcheck;
525#define DCHECK(condition) \
526 !logging::g_enable_dcheck ? void (0) : \
[email protected]fb62a532009-02-12 01:19:05527 LOG_IF(ERROR_REPORT, !(condition)) << "Check failed: " #condition ". "
initial.commitd7cae122008-07-26 21:49:38528
[email protected]d8617a62009-10-09 23:52:20529#define DPCHECK(condition) \
530 !logging::g_enable_dcheck ? void (0) : \
531 PLOG_IF(ERROR_REPORT, !(condition)) << "Check failed: " #condition ". "
532
initial.commitd7cae122008-07-26 21:49:38533// Helper macro for binary operators.
534// Don't use this macro directly in your code, use DCHECK_EQ et al below.
535#define DCHECK_OP(name, op, val1, val2) \
536 if (logging::g_enable_dcheck) \
537 if (logging::CheckOpString _result = \
538 logging::Check##name##Impl((val1), (val2), #val1 " " #op " " #val2)) \
[email protected]fb62a532009-02-12 01:19:05539 logging::LogMessage(__FILE__, __LINE__, logging::LOG_ERROR_REPORT, \
540 _result).stream()
initial.commitd7cae122008-07-26 21:49:38541
542#define DCHECK_STREQ(str1, str2) \
543 while (false) NDEBUG_EAT_STREAM_PARAMETERS
544
545#define DCHECK_STRCASEEQ(str1, str2) \
546 while (false) NDEBUG_EAT_STREAM_PARAMETERS
547
548#define DCHECK_STRNE(str1, str2) \
549 while (false) NDEBUG_EAT_STREAM_PARAMETERS
550
551#define DCHECK_STRCASENE(str1, str2) \
552 while (false) NDEBUG_EAT_STREAM_PARAMETERS
553
554#endif // NDEBUG
555
556// Helper functions for DCHECK_OP macro.
557// The (int, int) specialization works around the issue that the compiler
558// will not instantiate the template version of the function on values of
559// unnamed enum type - see comment below.
560#define DEFINE_DCHECK_OP_IMPL(name, op) \
561 template <class t1, class t2> \
562 inline std::string* Check##name##Impl(const t1& v1, const t2& v2, \
563 const char* names) { \
564 if (v1 op v2) return NULL; \
565 else return MakeCheckOpString(v1, v2, names); \
566 } \
567 inline std::string* Check##name##Impl(int v1, int v2, const char* names) { \
568 if (v1 op v2) return NULL; \
569 else return MakeCheckOpString(v1, v2, names); \
570 }
571DEFINE_DCHECK_OP_IMPL(EQ, ==)
572DEFINE_DCHECK_OP_IMPL(NE, !=)
573DEFINE_DCHECK_OP_IMPL(LE, <=)
574DEFINE_DCHECK_OP_IMPL(LT, < )
575DEFINE_DCHECK_OP_IMPL(GE, >=)
576DEFINE_DCHECK_OP_IMPL(GT, > )
577#undef DEFINE_DCHECK_OP_IMPL
578
579// Equality/Inequality checks - compare two values, and log a LOG_FATAL message
580// including the two values when the result is not as expected. The values
581// must have operator<<(ostream, ...) defined.
582//
583// You may append to the error message like so:
584// DCHECK_NE(1, 2) << ": The world must be ending!";
585//
586// We are very careful to ensure that each argument is evaluated exactly
587// once, and that anything which is legal to pass as a function argument is
588// legal here. In particular, the arguments may be temporary expressions
589// which will end up being destroyed at the end of the apparent statement,
590// for example:
591// DCHECK_EQ(string("abc")[1], 'b');
592//
593// WARNING: These may not compile correctly if one of the arguments is a pointer
594// and the other is NULL. To work around this, simply static_cast NULL to the
595// type of the desired pointer.
596
597#define DCHECK_EQ(val1, val2) DCHECK_OP(EQ, ==, val1, val2)
598#define DCHECK_NE(val1, val2) DCHECK_OP(NE, !=, val1, val2)
599#define DCHECK_LE(val1, val2) DCHECK_OP(LE, <=, val1, val2)
600#define DCHECK_LT(val1, val2) DCHECK_OP(LT, < , val1, val2)
601#define DCHECK_GE(val1, val2) DCHECK_OP(GE, >=, val1, val2)
602#define DCHECK_GT(val1, val2) DCHECK_OP(GT, > , val1, val2)
603
[email protected]e3cca332009-08-20 01:20:29604#endif // OMIT_DLOG_AND_DCHECK
605#undef OMIT_DLOG_AND_DCHECK
initial.commitd7cae122008-07-26 21:49:38606
607#define NOTREACHED() DCHECK(false)
608
609// Redefine the standard assert to use our nice log files
610#undef assert
611#define assert(x) DLOG_ASSERT(x)
612
613// This class more or less represents a particular log message. You
614// create an instance of LogMessage and then stream stuff to it.
615// When you finish streaming to it, ~LogMessage is called and the
616// full message gets streamed to the appropriate destination.
617//
618// You shouldn't actually use LogMessage's constructor to log things,
619// though. You should use the LOG() macro (and variants thereof)
620// above.
621class LogMessage {
622 public:
623 LogMessage(const char* file, int line, LogSeverity severity, int ctr);
624
625 // Two special constructors that generate reduced amounts of code at
626 // LOG call sites for common cases.
627 //
628 // Used for LOG(INFO): Implied are:
629 // severity = LOG_INFO, ctr = 0
630 //
631 // Using this constructor instead of the more complex constructor above
632 // saves a couple of bytes per call site.
633 LogMessage(const char* file, int line);
634
635 // Used for LOG(severity) where severity != INFO. Implied
636 // are: ctr = 0
637 //
638 // Using this constructor instead of the more complex constructor above
639 // saves a couple of bytes per call site.
640 LogMessage(const char* file, int line, LogSeverity severity);
641
642 // A special constructor used for check failures.
643 // Implied severity = LOG_FATAL
644 LogMessage(const char* file, int line, const CheckOpString& result);
645
[email protected]fb62a532009-02-12 01:19:05646 // A special constructor used for check failures, with the option to
647 // specify severity.
648 LogMessage(const char* file, int line, LogSeverity severity,
649 const CheckOpString& result);
650
initial.commitd7cae122008-07-26 21:49:38651 ~LogMessage();
652
653 std::ostream& stream() { return stream_; }
654
655 private:
656 void Init(const char* file, int line);
657
658 LogSeverity severity_;
659 std::ostringstream stream_;
[email protected]c88873922008-07-30 13:02:03660 size_t message_start_; // Offset of the start of the message (past prefix
661 // info).
[email protected]3f85caa2009-04-14 16:52:11662#if defined(OS_WIN)
663 // Stores the current value of GetLastError in the constructor and restores
664 // it in the destructor by calling SetLastError.
665 // This is useful since the LogMessage class uses a lot of Win32 calls
666 // that will lose the value of GLE and the code that called the log function
667 // will have lost the thread error value when the log call returns.
668 class SaveLastError {
669 public:
670 SaveLastError();
671 ~SaveLastError();
672
673 unsigned long get_error() const { return last_error_; }
674
675 protected:
676 unsigned long last_error_;
677 };
678
679 SaveLastError last_error_;
680#endif
initial.commitd7cae122008-07-26 21:49:38681
[email protected]39be4242008-08-07 18:31:40682 DISALLOW_COPY_AND_ASSIGN(LogMessage);
initial.commitd7cae122008-07-26 21:49:38683};
684
685// A non-macro interface to the log facility; (useful
686// when the logging level is not a compile-time constant).
687inline void LogAtLevel(int const log_level, std::string const &msg) {
688 LogMessage(__FILE__, __LINE__, log_level).stream() << msg;
689}
690
691// This class is used to explicitly ignore values in the conditional
692// logging macros. This avoids compiler warnings like "value computed
693// is not used" and "statement has no effect".
694class LogMessageVoidify {
695 public:
696 LogMessageVoidify() { }
697 // This has to be an operator with a precedence lower than << but
698 // higher than ?:
699 void operator&(std::ostream&) { }
700};
701
[email protected]d8617a62009-10-09 23:52:20702#if defined(OS_WIN)
703typedef unsigned long SystemErrorCode;
704#elif defined(OS_POSIX)
705typedef int SystemErrorCode;
706#endif
707
708// Alias for ::GetLastError() on Windows and errno on POSIX. Avoids having to
709// pull in windows.h just for GetLastError() and DWORD.
710SystemErrorCode GetLastSystemErrorCode();
711
712#if defined(OS_WIN)
713// Appends a formatted system message of the GetLastError() type.
714class Win32ErrorLogMessage {
715 public:
716 Win32ErrorLogMessage(const char* file,
717 int line,
718 LogSeverity severity,
719 SystemErrorCode err,
720 const char* module);
721
722 Win32ErrorLogMessage(const char* file,
723 int line,
724 LogSeverity severity,
725 SystemErrorCode err);
726
727 std::ostream& stream() { return log_message_.stream(); }
728
729 // Appends the error message before destructing the encapsulated class.
730 ~Win32ErrorLogMessage();
731
732 private:
733 SystemErrorCode err_;
734 // Optional name of the module defining the error.
735 const char* module_;
736 LogMessage log_message_;
737
738 DISALLOW_COPY_AND_ASSIGN(Win32ErrorLogMessage);
739};
740#elif defined(OS_POSIX)
741// Appends a formatted system message of the errno type
742class ErrnoLogMessage {
743 public:
744 ErrnoLogMessage(const char* file,
745 int line,
746 LogSeverity severity,
747 SystemErrorCode err);
748
749 std::ostream& stream() { return log_message_.stream(); }
750
751 // Appends the error message before destructing the encapsulated class.
752 ~ErrnoLogMessage();
753
754 private:
755 SystemErrorCode err_;
756 LogMessage log_message_;
757
758 DISALLOW_COPY_AND_ASSIGN(ErrnoLogMessage);
759};
760#endif // OS_WIN
761
initial.commitd7cae122008-07-26 21:49:38762// Closes the log file explicitly if open.
763// NOTE: Since the log file is opened as necessary by the action of logging
764// statements, there's no guarantee that it will stay closed
765// after this call.
766void CloseLogFile();
767
[email protected]39be4242008-08-07 18:31:40768} // namespace logging
initial.commitd7cae122008-07-26 21:49:38769
770// These functions are provided as a convenience for logging, which is where we
771// use streams (it is against Google style to use streams in other places). It
772// is designed to allow you to emit non-ASCII Unicode strings to the log file,
773// which is normally ASCII. It is relatively slow, so try not to use it for
[email protected]39be4242008-08-07 18:31:40774// common cases. Non-ASCII characters will be converted to UTF-8 by these
775// operators.
initial.commitd7cae122008-07-26 21:49:38776std::ostream& operator<<(std::ostream& out, const wchar_t* wstr);
777inline std::ostream& operator<<(std::ostream& out, const std::wstring& wstr) {
778 return out << wstr.c_str();
779}
780
[email protected]0dfc81b2008-08-25 03:44:40781// The NOTIMPLEMENTED() macro annotates codepaths which have
782// not been implemented yet.
783//
784// The implementation of this macro is controlled by NOTIMPLEMENTED_POLICY:
785// 0 -- Do nothing (stripped by compiler)
786// 1 -- Warn at compile time
787// 2 -- Fail at compile time
788// 3 -- Fail at runtime (DCHECK)
789// 4 -- [default] LOG(ERROR) at runtime
790// 5 -- LOG(ERROR) at runtime, only once per call-site
791
792#ifndef NOTIMPLEMENTED_POLICY
793// Select default policy: LOG(ERROR)
794#define NOTIMPLEMENTED_POLICY 4
795#endif
796
[email protected]f6cda752008-10-30 23:54:26797#if defined(COMPILER_GCC)
798// On Linux, with GCC, we can use __PRETTY_FUNCTION__ to get the demangled name
799// of the current function in the NOTIMPLEMENTED message.
800#define NOTIMPLEMENTED_MSG "Not implemented reached in " << __PRETTY_FUNCTION__
801#else
802#define NOTIMPLEMENTED_MSG "NOT IMPLEMENTED"
803#endif
804
[email protected]0dfc81b2008-08-25 03:44:40805#if NOTIMPLEMENTED_POLICY == 0
806#define NOTIMPLEMENTED() ;
807#elif NOTIMPLEMENTED_POLICY == 1
808// TODO, figure out how to generate a warning
809#define NOTIMPLEMENTED() COMPILE_ASSERT(false, NOT_IMPLEMENTED)
810#elif NOTIMPLEMENTED_POLICY == 2
811#define NOTIMPLEMENTED() COMPILE_ASSERT(false, NOT_IMPLEMENTED)
812#elif NOTIMPLEMENTED_POLICY == 3
813#define NOTIMPLEMENTED() NOTREACHED()
814#elif NOTIMPLEMENTED_POLICY == 4
[email protected]f6cda752008-10-30 23:54:26815#define NOTIMPLEMENTED() LOG(ERROR) << NOTIMPLEMENTED_MSG
[email protected]0dfc81b2008-08-25 03:44:40816#elif NOTIMPLEMENTED_POLICY == 5
817#define NOTIMPLEMENTED() do {\
818 static int count = 0;\
[email protected]f6cda752008-10-30 23:54:26819 LOG_IF(ERROR, 0 == count++) << NOTIMPLEMENTED_MSG;\
[email protected]0dfc81b2008-08-25 03:44:40820} while(0)
821#endif
822
[email protected]39be4242008-08-07 18:31:40823#endif // BASE_LOGGING_H_