blob: baedb8b5552c15d97c189394edad7b3dee3b67d2 [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"
13#include "base/scoped_ptr.h"
14
15//
16// Optional message capabilities
17// -----------------------------
18// Assertion failed messages and fatal errors are displayed in a dialog box
19// before the application exits. However, running this UI creates a message
20// loop, which causes application messages to be processed and potentially
21// dispatched to existing application windows. Since the application is in a
22// bad state when this assertion dialog is displayed, these messages may not
23// get processed and hang the dialog, or the application might go crazy.
24//
25// Therefore, it can be beneficial to display the error dialog in a separate
26// process from the main application. When the logging system needs to display
27// a fatal error dialog box, it will look for a program called
28// "DebugMessage.exe" in the same directory as the application executable. It
29// will run this application with the message as the command line, and will
30// not include the name of the application as is traditional for easier
31// parsing.
32//
33// The code for DebugMessage.exe is only one line. In WinMain, do:
34// MessageBox(NULL, GetCommandLineW(), L"Fatal Error", 0);
35//
36// If DebugMessage.exe is not found, the logging code will use a normal
37// MessageBox, potentially causing the problems discussed above.
38
39
40// Instructions
41// ------------
42//
43// Make a bunch of macros for logging. The way to log things is to stream
44// things to LOG(<a particular severity level>). E.g.,
45//
46// LOG(INFO) << "Found " << num_cookies << " cookies";
47//
48// You can also do conditional logging:
49//
50// LOG_IF(INFO, num_cookies > 10) << "Got lots of cookies";
51//
52// The above will cause log messages to be output on the 1st, 11th, 21st, ...
53// times it is executed. Note that the special COUNTER value is used to
54// identify which repetition is happening.
55//
56// The CHECK(condition) macro is active in both debug and release builds and
57// effectively performs a LOG(FATAL) which terminates the process and
58// generates a crashdump unless a debugger is attached.
59//
60// There are also "debug mode" logging macros like the ones above:
61//
62// DLOG(INFO) << "Found cookies";
63//
64// DLOG_IF(INFO, num_cookies > 10) << "Got lots of cookies";
65//
66// All "debug mode" logging is compiled away to nothing for non-debug mode
67// compiles. LOG_IF and development flags also work well together
68// because the code can be compiled away sometimes.
69//
70// We also have
71//
72// LOG_ASSERT(assertion);
73// DLOG_ASSERT(assertion);
74//
75// which is syntactic sugar for {,D}LOG_IF(FATAL, assert fails) << assertion;
76//
77// We also override the standard 'assert' to use 'DLOG_ASSERT'.
78//
79// The supported severity levels for macros that allow you to specify one
[email protected]fb62a532009-02-12 01:19:0580// are (in increasing order of severity) INFO, WARNING, ERROR, ERROR_REPORT,
81// and FATAL.
initial.commitd7cae122008-07-26 21:49:3882//
83// Very important: logging a message at the FATAL severity level causes
84// the program to terminate (after the message is logged).
[email protected]fb62a532009-02-12 01:19:0585//
86// Note the special severity of ERROR_REPORT only available/relevant in normal
87// mode, which displays error dialog without terminating the program. There is
88// no error dialog for severity ERROR or below in normal mode.
89//
90// There is also the special severity of DFATAL, which logs FATAL in
91// debug mode, ERROR_REPORT in normal mode.
initial.commitd7cae122008-07-26 21:49:3892
93namespace logging {
94
95// Where to record logging output? A flat file and/or system debug log via
[email protected]88aa41e82008-11-18 00:59:0496// OutputDebugString. Defaults on Windows to LOG_ONLY_TO_FILE, and on
97// POSIX to LOG_ONLY_TO_SYSTEM_DEBUG_LOG (aka stderr).
initial.commitd7cae122008-07-26 21:49:3898enum LoggingDestination { LOG_NONE,
99 LOG_ONLY_TO_FILE,
100 LOG_ONLY_TO_SYSTEM_DEBUG_LOG,
101 LOG_TO_BOTH_FILE_AND_SYSTEM_DEBUG_LOG };
102
103// Indicates that the log file should be locked when being written to.
104// Often, there is no locking, which is fine for a single threaded program.
105// If logging is being done from multiple threads or there can be more than
106// one process doing the logging, the file should be locked during writes to
107// make each log outut atomic. Other writers will block.
108//
109// All processes writing to the log file must have their locking set for it to
110// work properly. Defaults to DONT_LOCK_LOG_FILE.
111enum LogLockingState { LOCK_LOG_FILE, DONT_LOCK_LOG_FILE };
112
113// On startup, should we delete or append to an existing log file (if any)?
114// Defaults to APPEND_TO_OLD_LOG_FILE.
115enum OldFileDeletionState { DELETE_OLD_LOG_FILE, APPEND_TO_OLD_LOG_FILE };
116
117// Sets the log file name and other global logging state. Calling this function
118// is recommended, and is normally done at the beginning of application init.
119// If you don't call it, all the flags will be initialized to their default
120// values, and there is a race condition that may leak a critical section
121// object if two threads try to do the first log at the same time.
122// See the definition of the enums above for descriptions and default values.
123//
124// The default log file is initialized to "debug.log" in the application
125// directory. You probably don't want this, especially since the program
126// directory may not be writable on an enduser's system.
[email protected]39be4242008-08-07 18:31:40127#if defined(OS_WIN)
initial.commitd7cae122008-07-26 21:49:38128void InitLogging(const wchar_t* log_file, LoggingDestination logging_dest,
129 LogLockingState lock_log, OldFileDeletionState delete_old);
[email protected]39be4242008-08-07 18:31:40130#elif defined(OS_POSIX)
initial.commitd7cae122008-07-26 21:49:38131// TODO(avi): do we want to do a unification of character types here?
132void InitLogging(const char* log_file, LoggingDestination logging_dest,
133 LogLockingState lock_log, OldFileDeletionState delete_old);
134#endif
135
136// Sets the log level. Anything at or above this level will be written to the
137// log file/displayed to the user (if applicable). Anything below this level
138// will be silently ignored. The log level defaults to 0 (everything is logged)
139// if this function is not called.
140void SetMinLogLevel(int level);
141
142// Gets the curreng log level.
143int GetMinLogLevel();
144
145// Sets the log filter prefix. Any log message below LOG_ERROR severity that
146// doesn't start with this prefix with be silently ignored. The filter defaults
147// to NULL (everything is logged) if this function is not called. Messages
148// with severity of LOG_ERROR or higher will not be filtered.
149void SetLogFilterPrefix(const char* filter);
150
151// Sets the common items you want to be prepended to each log message.
152// process and thread IDs default to off, the timestamp defaults to on.
153// If this function is not called, logging defaults to writing the timestamp
154// only.
155void SetLogItems(bool enable_process_id, bool enable_thread_id,
156 bool enable_timestamp, bool enable_tickcount);
157
158// Sets the Log Assert Handler that will be used to notify of check failures.
[email protected]fb62a532009-02-12 01:19:05159// The default handler shows a dialog box and then terminate the process,
160// however clients can use this function to override with their own handling
161// (e.g. a silent one for Unit Tests)
initial.commitd7cae122008-07-26 21:49:38162typedef void (*LogAssertHandlerFunction)(const std::string& str);
163void SetLogAssertHandler(LogAssertHandlerFunction handler);
[email protected]fb62a532009-02-12 01:19:05164// Sets the Log Report Handler that will be used to notify of check failures
165// in non-debug mode. The default handler shows a dialog box and continues
166// the execution, however clients can use this function to override with their
167// own handling.
168typedef void (*LogReportHandlerFunction)(const std::string& str);
169void SetLogReportHandler(LogReportHandlerFunction handler);
initial.commitd7cae122008-07-26 21:49:38170
171typedef int LogSeverity;
172const LogSeverity LOG_INFO = 0;
173const LogSeverity LOG_WARNING = 1;
174const LogSeverity LOG_ERROR = 2;
[email protected]fb62a532009-02-12 01:19:05175const LogSeverity LOG_ERROR_REPORT = 3;
176const LogSeverity LOG_FATAL = 4;
177const LogSeverity LOG_NUM_SEVERITIES = 5;
initial.commitd7cae122008-07-26 21:49:38178
[email protected]fb62a532009-02-12 01:19:05179// LOG_DFATAL_LEVEL is LOG_FATAL in debug mode, ERROR_REPORT in normal mode
initial.commitd7cae122008-07-26 21:49:38180#ifdef NDEBUG
[email protected]fb62a532009-02-12 01:19:05181const LogSeverity LOG_DFATAL_LEVEL = LOG_ERROR_REPORT;
initial.commitd7cae122008-07-26 21:49:38182#else
183const LogSeverity LOG_DFATAL_LEVEL = LOG_FATAL;
184#endif
185
186// A few definitions of macros that don't generate much code. These are used
187// by LOG() and LOG_IF, etc. Since these are used all over our code, it's
188// better to have compact code for these operations.
189#define COMPACT_GOOGLE_LOG_INFO \
190 logging::LogMessage(__FILE__, __LINE__)
191#define COMPACT_GOOGLE_LOG_WARNING \
192 logging::LogMessage(__FILE__, __LINE__, logging::LOG_WARNING)
193#define COMPACT_GOOGLE_LOG_ERROR \
194 logging::LogMessage(__FILE__, __LINE__, logging::LOG_ERROR)
[email protected]fb62a532009-02-12 01:19:05195#define COMPACT_GOOGLE_LOG_ERROR_REPORT \
196 logging::LogMessage(__FILE__, __LINE__, logging::LOG_ERROR_REPORT)
initial.commitd7cae122008-07-26 21:49:38197#define COMPACT_GOOGLE_LOG_FATAL \
198 logging::LogMessage(__FILE__, __LINE__, logging::LOG_FATAL)
199#define COMPACT_GOOGLE_LOG_DFATAL \
200 logging::LogMessage(__FILE__, __LINE__, logging::LOG_DFATAL_LEVEL)
201
202// wingdi.h defines ERROR to be 0. When we call LOG(ERROR), it gets
203// substituted with 0, and it expands to COMPACT_GOOGLE_LOG_0. To allow us
204// to keep using this syntax, we define this macro to do the same thing
205// as COMPACT_GOOGLE_LOG_ERROR, and also define ERROR the same way that
206// the Windows SDK does for consistency.
207#define ERROR 0
208#define COMPACT_GOOGLE_LOG_0 \
209 logging::LogMessage(__FILE__, __LINE__, logging::LOG_ERROR)
210
211// We use the preprocessor's merging operator, "##", so that, e.g.,
212// LOG(INFO) becomes the token COMPACT_GOOGLE_LOG_INFO. There's some funny
213// subtle difference between ostream member streaming functions (e.g.,
214// ostream::operator<<(int) and ostream non-member streaming functions
215// (e.g., ::operator<<(ostream&, string&): it turns out that it's
216// impossible to stream something like a string directly to an unnamed
217// ostream. We employ a neat hack by calling the stream() member
218// function of LogMessage which seems to avoid the problem.
219
220#define LOG(severity) COMPACT_GOOGLE_LOG_ ## severity.stream()
221#define SYSLOG(severity) LOG(severity)
222
223#define LOG_IF(severity, condition) \
224 !(condition) ? (void) 0 : logging::LogMessageVoidify() & LOG(severity)
225#define SYSLOG_IF(severity, condition) LOG_IF(severity, condition)
226
227#define LOG_ASSERT(condition) \
228 LOG_IF(FATAL, !(condition)) << "Assert failed: " #condition ". "
229#define SYSLOG_ASSERT(condition) \
230 SYSLOG_IF(FATAL, !(condition)) << "Assert failed: " #condition ". "
231
232// CHECK dies with a fatal error if condition is not true. It is *not*
233// controlled by NDEBUG, so the check will be executed regardless of
234// compilation mode.
235#define CHECK(condition) \
236 LOG_IF(FATAL, !(condition)) << "Check failed: " #condition ". "
237
238// A container for a string pointer which can be evaluated to a bool -
239// true iff the pointer is NULL.
240struct CheckOpString {
241 CheckOpString(std::string* str) : str_(str) { }
242 // No destructor: if str_ is non-NULL, we're about to LOG(FATAL),
243 // so there's no point in cleaning up str_.
244 operator bool() const { return str_ != NULL; }
245 std::string* str_;
246};
247
248// Build the error message string. This is separate from the "Impl"
249// function template because it is not performance critical and so can
250// be out of line, while the "Impl" code should be inline.
251template<class t1, class t2>
252std::string* MakeCheckOpString(const t1& v1, const t2& v2, const char* names) {
253 std::ostringstream ss;
254 ss << names << " (" << v1 << " vs. " << v2 << ")";
255 std::string* msg = new std::string(ss.str());
256 return msg;
257}
258
259extern std::string* MakeCheckOpStringIntInt(int v1, int v2, const char* names);
260
261template<int, int>
262std::string* MakeCheckOpString(const int& v1, const int& v2, const char* names) {
263 return MakeCheckOpStringIntInt(v1, v2, names);
264}
265
266// Plus some debug-logging macros that get compiled to nothing for production
267//
268// DEBUG_MODE is for uses like
269// if (DEBUG_MODE) foo.CheckThatFoo();
270// instead of
271// #ifndef NDEBUG
272// foo.CheckThatFoo();
273// #endif
274
[email protected]94558e632008-12-11 22:10:17275#ifdef OFFICIAL_BUILD
276// We want to have optimized code for an official build so we remove DLOGS and
277// DCHECK from the executable.
278
279#define DLOG(severity) \
280 true ? (void) 0 : logging::LogMessageVoidify() & LOG(severity)
281
282#define DLOG_IF(severity, condition) \
283 true ? (void) 0 : logging::LogMessageVoidify() & LOG(severity)
284
285#define DLOG_ASSERT(condition) \
286 true ? (void) 0 : LOG_ASSERT(condition)
287
288enum { DEBUG_MODE = 0 };
289
290// This macro can be followed by a sequence of stream parameters in
291// non-debug mode. The DCHECK and friends macros use this so that
292// the expanded expression DCHECK(foo) << "asdf" is still syntactically
293// valid, even though the expression will get optimized away.
[email protected]8c1766b92009-01-26 16:34:49294// In order to avoid variable unused warnings for code that only uses a
295// variable in a CHECK, we make sure to use the macro arguments.
[email protected]94558e632008-12-11 22:10:17296#define NDEBUG_EAT_STREAM_PARAMETERS \
297 logging::LogMessage(__FILE__, __LINE__).stream()
298
299#define DCHECK(condition) \
[email protected]8c1766b92009-01-26 16:34:49300 while (false && (condition)) NDEBUG_EAT_STREAM_PARAMETERS
[email protected]94558e632008-12-11 22:10:17301
302#define DCHECK_EQ(val1, val2) \
[email protected]8c1766b92009-01-26 16:34:49303 while (false && (val1) == (val2)) NDEBUG_EAT_STREAM_PARAMETERS
[email protected]94558e632008-12-11 22:10:17304
305#define DCHECK_NE(val1, val2) \
[email protected]8c1766b92009-01-26 16:34:49306 while (false && (val1) == (val2)) NDEBUG_EAT_STREAM_PARAMETERS
[email protected]94558e632008-12-11 22:10:17307
308#define DCHECK_LE(val1, val2) \
[email protected]8c1766b92009-01-26 16:34:49309 while (false && (val1) == (val2)) NDEBUG_EAT_STREAM_PARAMETERS
[email protected]94558e632008-12-11 22:10:17310
311#define DCHECK_LT(val1, val2) \
[email protected]8c1766b92009-01-26 16:34:49312 while (false && (val1) == (val2)) NDEBUG_EAT_STREAM_PARAMETERS
[email protected]94558e632008-12-11 22:10:17313
314#define DCHECK_GE(val1, val2) \
[email protected]8c1766b92009-01-26 16:34:49315 while (false && (val1) == (val2)) NDEBUG_EAT_STREAM_PARAMETERS
[email protected]94558e632008-12-11 22:10:17316
317#define DCHECK_GT(val1, val2) \
[email protected]8c1766b92009-01-26 16:34:49318 while (false && (val1) == (val2)) NDEBUG_EAT_STREAM_PARAMETERS
[email protected]94558e632008-12-11 22:10:17319
320#define DCHECK_STREQ(str1, str2) \
[email protected]8c1766b92009-01-26 16:34:49321 while (false && (str1) == (str2)) NDEBUG_EAT_STREAM_PARAMETERS
[email protected]94558e632008-12-11 22:10:17322
323#define DCHECK_STRCASEEQ(str1, str2) \
[email protected]8c1766b92009-01-26 16:34:49324 while (false && (str1) == (str2)) NDEBUG_EAT_STREAM_PARAMETERS
[email protected]94558e632008-12-11 22:10:17325
326#define DCHECK_STRNE(str1, str2) \
[email protected]8c1766b92009-01-26 16:34:49327 while (false && (str1) == (str2)) NDEBUG_EAT_STREAM_PARAMETERS
[email protected]94558e632008-12-11 22:10:17328
329#define DCHECK_STRCASENE(str1, str2) \
[email protected]8c1766b92009-01-26 16:34:49330 while (false && (str1) == (str2)) NDEBUG_EAT_STREAM_PARAMETERS
[email protected]94558e632008-12-11 22:10:17331
332#else
initial.commitd7cae122008-07-26 21:49:38333#ifndef NDEBUG
[email protected]94558e632008-12-11 22:10:17334// On a regular debug build, we want to have DCHECKS and DLOGS enabled.
initial.commitd7cae122008-07-26 21:49:38335
336#define DLOG(severity) LOG(severity)
337#define DLOG_IF(severity, condition) LOG_IF(severity, condition)
338#define DLOG_ASSERT(condition) LOG_ASSERT(condition)
339
340// debug-only checking. not executed in NDEBUG mode.
341enum { DEBUG_MODE = 1 };
342#define DCHECK(condition) \
343 LOG_IF(FATAL, !(condition)) << "Check failed: " #condition ". "
344
345// Helper macro for binary operators.
346// Don't use this macro directly in your code, use DCHECK_EQ et al below.
347#define DCHECK_OP(name, op, val1, val2) \
348 if (logging::CheckOpString _result = \
349 logging::Check##name##Impl((val1), (val2), #val1 " " #op " " #val2)) \
350 logging::LogMessage(__FILE__, __LINE__, _result).stream()
351
352// Helper functions for string comparisons.
353// To avoid bloat, the definitions are in logging.cc.
354#define DECLARE_DCHECK_STROP_IMPL(func, expected) \
355 std::string* Check##func##expected##Impl(const char* s1, \
356 const char* s2, \
357 const char* names);
358DECLARE_DCHECK_STROP_IMPL(strcmp, true)
359DECLARE_DCHECK_STROP_IMPL(strcmp, false)
360DECLARE_DCHECK_STROP_IMPL(_stricmp, true)
361DECLARE_DCHECK_STROP_IMPL(_stricmp, false)
362#undef DECLARE_DCHECK_STROP_IMPL
363
364// Helper macro for string comparisons.
365// Don't use this macro directly in your code, use CHECK_STREQ et al below.
366#define DCHECK_STROP(func, op, expected, s1, s2) \
367 while (CheckOpString _result = \
368 logging::Check##func##expected##Impl((s1), (s2), \
369 #s1 " " #op " " #s2)) \
370 LOG(FATAL) << *_result.str_
371
372// String (char*) equality/inequality checks.
373// CASE versions are case-insensitive.
374//
375// Note that "s1" and "s2" may be temporary strings which are destroyed
376// by the compiler at the end of the current "full expression"
377// (e.g. DCHECK_STREQ(Foo().c_str(), Bar().c_str())).
378
379#define DCHECK_STREQ(s1, s2) DCHECK_STROP(strcmp, ==, true, s1, s2)
380#define DCHECK_STRNE(s1, s2) DCHECK_STROP(strcmp, !=, false, s1, s2)
381#define DCHECK_STRCASEEQ(s1, s2) DCHECK_STROP(_stricmp, ==, true, s1, s2)
382#define DCHECK_STRCASENE(s1, s2) DCHECK_STROP(_stricmp, !=, false, s1, s2)
383
384#define DCHECK_INDEX(I,A) DCHECK(I < (sizeof(A)/sizeof(A[0])))
385#define DCHECK_BOUND(B,A) DCHECK(B <= (sizeof(A)/sizeof(A[0])))
386
387#else // NDEBUG
[email protected]94558e632008-12-11 22:10:17388// On a regular release build we want to be able to enable DCHECKS through the
389// command line.
initial.commitd7cae122008-07-26 21:49:38390#define DLOG(severity) \
391 true ? (void) 0 : logging::LogMessageVoidify() & LOG(severity)
392
393#define DLOG_IF(severity, condition) \
394 true ? (void) 0 : logging::LogMessageVoidify() & LOG(severity)
395
396#define DLOG_ASSERT(condition) \
397 true ? (void) 0 : LOG_ASSERT(condition)
398
399enum { DEBUG_MODE = 0 };
400
401// This macro can be followed by a sequence of stream parameters in
402// non-debug mode. The DCHECK and friends macros use this so that
403// the expanded expression DCHECK(foo) << "asdf" is still syntactically
404// valid, even though the expression will get optimized away.
405#define NDEBUG_EAT_STREAM_PARAMETERS \
406 logging::LogMessage(__FILE__, __LINE__).stream()
407
408// Set to true in InitLogging when we want to enable the dchecks in release.
409extern bool g_enable_dcheck;
410#define DCHECK(condition) \
411 !logging::g_enable_dcheck ? void (0) : \
[email protected]fb62a532009-02-12 01:19:05412 LOG_IF(ERROR_REPORT, !(condition)) << "Check failed: " #condition ". "
initial.commitd7cae122008-07-26 21:49:38413
414// Helper macro for binary operators.
415// Don't use this macro directly in your code, use DCHECK_EQ et al below.
416#define DCHECK_OP(name, op, val1, val2) \
417 if (logging::g_enable_dcheck) \
418 if (logging::CheckOpString _result = \
419 logging::Check##name##Impl((val1), (val2), #val1 " " #op " " #val2)) \
[email protected]fb62a532009-02-12 01:19:05420 logging::LogMessage(__FILE__, __LINE__, logging::LOG_ERROR_REPORT, \
421 _result).stream()
initial.commitd7cae122008-07-26 21:49:38422
423#define DCHECK_STREQ(str1, str2) \
424 while (false) NDEBUG_EAT_STREAM_PARAMETERS
425
426#define DCHECK_STRCASEEQ(str1, str2) \
427 while (false) NDEBUG_EAT_STREAM_PARAMETERS
428
429#define DCHECK_STRNE(str1, str2) \
430 while (false) NDEBUG_EAT_STREAM_PARAMETERS
431
432#define DCHECK_STRCASENE(str1, str2) \
433 while (false) NDEBUG_EAT_STREAM_PARAMETERS
434
435#endif // NDEBUG
436
437// Helper functions for DCHECK_OP macro.
438// The (int, int) specialization works around the issue that the compiler
439// will not instantiate the template version of the function on values of
440// unnamed enum type - see comment below.
441#define DEFINE_DCHECK_OP_IMPL(name, op) \
442 template <class t1, class t2> \
443 inline std::string* Check##name##Impl(const t1& v1, const t2& v2, \
444 const char* names) { \
445 if (v1 op v2) return NULL; \
446 else return MakeCheckOpString(v1, v2, names); \
447 } \
448 inline std::string* Check##name##Impl(int v1, int v2, const char* names) { \
449 if (v1 op v2) return NULL; \
450 else return MakeCheckOpString(v1, v2, names); \
451 }
452DEFINE_DCHECK_OP_IMPL(EQ, ==)
453DEFINE_DCHECK_OP_IMPL(NE, !=)
454DEFINE_DCHECK_OP_IMPL(LE, <=)
455DEFINE_DCHECK_OP_IMPL(LT, < )
456DEFINE_DCHECK_OP_IMPL(GE, >=)
457DEFINE_DCHECK_OP_IMPL(GT, > )
458#undef DEFINE_DCHECK_OP_IMPL
459
460// Equality/Inequality checks - compare two values, and log a LOG_FATAL message
461// including the two values when the result is not as expected. The values
462// must have operator<<(ostream, ...) defined.
463//
464// You may append to the error message like so:
465// DCHECK_NE(1, 2) << ": The world must be ending!";
466//
467// We are very careful to ensure that each argument is evaluated exactly
468// once, and that anything which is legal to pass as a function argument is
469// legal here. In particular, the arguments may be temporary expressions
470// which will end up being destroyed at the end of the apparent statement,
471// for example:
472// DCHECK_EQ(string("abc")[1], 'b');
473//
474// WARNING: These may not compile correctly if one of the arguments is a pointer
475// and the other is NULL. To work around this, simply static_cast NULL to the
476// type of the desired pointer.
477
478#define DCHECK_EQ(val1, val2) DCHECK_OP(EQ, ==, val1, val2)
479#define DCHECK_NE(val1, val2) DCHECK_OP(NE, !=, val1, val2)
480#define DCHECK_LE(val1, val2) DCHECK_OP(LE, <=, val1, val2)
481#define DCHECK_LT(val1, val2) DCHECK_OP(LT, < , val1, val2)
482#define DCHECK_GE(val1, val2) DCHECK_OP(GE, >=, val1, val2)
483#define DCHECK_GT(val1, val2) DCHECK_OP(GT, > , val1, val2)
484
[email protected]94558e632008-12-11 22:10:17485#endif // OFFICIAL_BUILD
initial.commitd7cae122008-07-26 21:49:38486
487#define NOTREACHED() DCHECK(false)
488
489// Redefine the standard assert to use our nice log files
490#undef assert
491#define assert(x) DLOG_ASSERT(x)
492
493// This class more or less represents a particular log message. You
494// create an instance of LogMessage and then stream stuff to it.
495// When you finish streaming to it, ~LogMessage is called and the
496// full message gets streamed to the appropriate destination.
497//
498// You shouldn't actually use LogMessage's constructor to log things,
499// though. You should use the LOG() macro (and variants thereof)
500// above.
501class LogMessage {
502 public:
503 LogMessage(const char* file, int line, LogSeverity severity, int ctr);
504
505 // Two special constructors that generate reduced amounts of code at
506 // LOG call sites for common cases.
507 //
508 // Used for LOG(INFO): Implied are:
509 // severity = LOG_INFO, ctr = 0
510 //
511 // Using this constructor instead of the more complex constructor above
512 // saves a couple of bytes per call site.
513 LogMessage(const char* file, int line);
514
515 // Used for LOG(severity) where severity != INFO. Implied
516 // are: ctr = 0
517 //
518 // Using this constructor instead of the more complex constructor above
519 // saves a couple of bytes per call site.
520 LogMessage(const char* file, int line, LogSeverity severity);
521
522 // A special constructor used for check failures.
523 // Implied severity = LOG_FATAL
524 LogMessage(const char* file, int line, const CheckOpString& result);
525
[email protected]fb62a532009-02-12 01:19:05526 // A special constructor used for check failures, with the option to
527 // specify severity.
528 LogMessage(const char* file, int line, LogSeverity severity,
529 const CheckOpString& result);
530
initial.commitd7cae122008-07-26 21:49:38531 ~LogMessage();
532
533 std::ostream& stream() { return stream_; }
534
535 private:
536 void Init(const char* file, int line);
537
538 LogSeverity severity_;
539 std::ostringstream stream_;
[email protected]c88873922008-07-30 13:02:03540 size_t message_start_; // Offset of the start of the message (past prefix
541 // info).
initial.commitd7cae122008-07-26 21:49:38542
[email protected]39be4242008-08-07 18:31:40543 DISALLOW_COPY_AND_ASSIGN(LogMessage);
initial.commitd7cae122008-07-26 21:49:38544};
545
546// A non-macro interface to the log facility; (useful
547// when the logging level is not a compile-time constant).
548inline void LogAtLevel(int const log_level, std::string const &msg) {
549 LogMessage(__FILE__, __LINE__, log_level).stream() << msg;
550}
551
552// This class is used to explicitly ignore values in the conditional
553// logging macros. This avoids compiler warnings like "value computed
554// is not used" and "statement has no effect".
555class LogMessageVoidify {
556 public:
557 LogMessageVoidify() { }
558 // This has to be an operator with a precedence lower than << but
559 // higher than ?:
560 void operator&(std::ostream&) { }
561};
562
563// Closes the log file explicitly if open.
564// NOTE: Since the log file is opened as necessary by the action of logging
565// statements, there's no guarantee that it will stay closed
566// after this call.
567void CloseLogFile();
568
[email protected]39be4242008-08-07 18:31:40569} // namespace logging
initial.commitd7cae122008-07-26 21:49:38570
571// These functions are provided as a convenience for logging, which is where we
572// use streams (it is against Google style to use streams in other places). It
573// is designed to allow you to emit non-ASCII Unicode strings to the log file,
574// which is normally ASCII. It is relatively slow, so try not to use it for
[email protected]39be4242008-08-07 18:31:40575// common cases. Non-ASCII characters will be converted to UTF-8 by these
576// operators.
initial.commitd7cae122008-07-26 21:49:38577std::ostream& operator<<(std::ostream& out, const wchar_t* wstr);
578inline std::ostream& operator<<(std::ostream& out, const std::wstring& wstr) {
579 return out << wstr.c_str();
580}
581
[email protected]0dfc81b2008-08-25 03:44:40582// The NOTIMPLEMENTED() macro annotates codepaths which have
583// not been implemented yet.
584//
585// The implementation of this macro is controlled by NOTIMPLEMENTED_POLICY:
586// 0 -- Do nothing (stripped by compiler)
587// 1 -- Warn at compile time
588// 2 -- Fail at compile time
589// 3 -- Fail at runtime (DCHECK)
590// 4 -- [default] LOG(ERROR) at runtime
591// 5 -- LOG(ERROR) at runtime, only once per call-site
592
593#ifndef NOTIMPLEMENTED_POLICY
594// Select default policy: LOG(ERROR)
595#define NOTIMPLEMENTED_POLICY 4
596#endif
597
[email protected]f6cda752008-10-30 23:54:26598#if defined(COMPILER_GCC)
599// On Linux, with GCC, we can use __PRETTY_FUNCTION__ to get the demangled name
600// of the current function in the NOTIMPLEMENTED message.
601#define NOTIMPLEMENTED_MSG "Not implemented reached in " << __PRETTY_FUNCTION__
602#else
603#define NOTIMPLEMENTED_MSG "NOT IMPLEMENTED"
604#endif
605
[email protected]0dfc81b2008-08-25 03:44:40606#if NOTIMPLEMENTED_POLICY == 0
607#define NOTIMPLEMENTED() ;
608#elif NOTIMPLEMENTED_POLICY == 1
609// TODO, figure out how to generate a warning
610#define NOTIMPLEMENTED() COMPILE_ASSERT(false, NOT_IMPLEMENTED)
611#elif NOTIMPLEMENTED_POLICY == 2
612#define NOTIMPLEMENTED() COMPILE_ASSERT(false, NOT_IMPLEMENTED)
613#elif NOTIMPLEMENTED_POLICY == 3
614#define NOTIMPLEMENTED() NOTREACHED()
615#elif NOTIMPLEMENTED_POLICY == 4
[email protected]f6cda752008-10-30 23:54:26616#define NOTIMPLEMENTED() LOG(ERROR) << NOTIMPLEMENTED_MSG
[email protected]0dfc81b2008-08-25 03:44:40617#elif NOTIMPLEMENTED_POLICY == 5
618#define NOTIMPLEMENTED() do {\
619 static int count = 0;\
[email protected]f6cda752008-10-30 23:54:26620 LOG_IF(ERROR, 0 == count++) << NOTIMPLEMENTED_MSG;\
[email protected]0dfc81b2008-08-25 03:44:40621} while(0)
622#endif
623
[email protected]39be4242008-08-07 18:31:40624#endif // BASE_LOGGING_H_