blob: 168bc32f4cbd33addaa0d785e838801bb092d9b0 [file] [log] [blame]
license.botf003cfe2008-08-24 09:55:55 +09001// 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.commit3f4a7322008-07-27 06:49:38 +09004
brettw@google.come3c034a2008-08-08 03:31:40 +09005#ifndef BASE_LOGGING_H_
6#define BASE_LOGGING_H_
initial.commit3f4a7322008-07-27 06:49:38 +09007
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
80// are (in increasing order of severity) INFO, WARNING, ERROR, and FATAL.
81//
82// There is also the special severity of DFATAL, which logs FATAL in
83// debug mode, ERROR in normal mode.
84//
85// Very important: logging a message at the FATAL severity level causes
86// the program to terminate (after the message is logged).
87
88namespace logging {
89
90// Where to record logging output? A flat file and/or system debug log via
91// OutputDebugString. Defaults to LOG_ONLY_TO_FILE.
92enum LoggingDestination { LOG_NONE,
93 LOG_ONLY_TO_FILE,
94 LOG_ONLY_TO_SYSTEM_DEBUG_LOG,
95 LOG_TO_BOTH_FILE_AND_SYSTEM_DEBUG_LOG };
96
97// Indicates that the log file should be locked when being written to.
98// Often, there is no locking, which is fine for a single threaded program.
99// If logging is being done from multiple threads or there can be more than
100// one process doing the logging, the file should be locked during writes to
101// make each log outut atomic. Other writers will block.
102//
103// All processes writing to the log file must have their locking set for it to
104// work properly. Defaults to DONT_LOCK_LOG_FILE.
105enum LogLockingState { LOCK_LOG_FILE, DONT_LOCK_LOG_FILE };
106
107// On startup, should we delete or append to an existing log file (if any)?
108// Defaults to APPEND_TO_OLD_LOG_FILE.
109enum OldFileDeletionState { DELETE_OLD_LOG_FILE, APPEND_TO_OLD_LOG_FILE };
110
111// Sets the log file name and other global logging state. Calling this function
112// is recommended, and is normally done at the beginning of application init.
113// If you don't call it, all the flags will be initialized to their default
114// values, and there is a race condition that may leak a critical section
115// object if two threads try to do the first log at the same time.
116// See the definition of the enums above for descriptions and default values.
117//
118// The default log file is initialized to "debug.log" in the application
119// directory. You probably don't want this, especially since the program
120// directory may not be writable on an enduser's system.
brettw@google.come3c034a2008-08-08 03:31:40 +0900121#if defined(OS_WIN)
initial.commit3f4a7322008-07-27 06:49:38 +0900122void InitLogging(const wchar_t* log_file, LoggingDestination logging_dest,
123 LogLockingState lock_log, OldFileDeletionState delete_old);
brettw@google.come3c034a2008-08-08 03:31:40 +0900124#elif defined(OS_POSIX)
initial.commit3f4a7322008-07-27 06:49:38 +0900125// TODO(avi): do we want to do a unification of character types here?
126void InitLogging(const char* log_file, LoggingDestination logging_dest,
127 LogLockingState lock_log, OldFileDeletionState delete_old);
128#endif
129
130// Sets the log level. Anything at or above this level will be written to the
131// log file/displayed to the user (if applicable). Anything below this level
132// will be silently ignored. The log level defaults to 0 (everything is logged)
133// if this function is not called.
134void SetMinLogLevel(int level);
135
136// Gets the curreng log level.
137int GetMinLogLevel();
138
139// Sets the log filter prefix. Any log message below LOG_ERROR severity that
140// doesn't start with this prefix with be silently ignored. The filter defaults
141// to NULL (everything is logged) if this function is not called. Messages
142// with severity of LOG_ERROR or higher will not be filtered.
143void SetLogFilterPrefix(const char* filter);
144
145// Sets the common items you want to be prepended to each log message.
146// process and thread IDs default to off, the timestamp defaults to on.
147// If this function is not called, logging defaults to writing the timestamp
148// only.
149void SetLogItems(bool enable_process_id, bool enable_thread_id,
150 bool enable_timestamp, bool enable_tickcount);
151
152// Sets the Log Assert Handler that will be used to notify of check failures.
153// The default handler shows a dialog box, however clients can use this
154// function to override with their own handling (e.g. a silent one for Unit
155// Tests)
156typedef void (*LogAssertHandlerFunction)(const std::string& str);
157void SetLogAssertHandler(LogAssertHandlerFunction handler);
158
159typedef int LogSeverity;
160const LogSeverity LOG_INFO = 0;
161const LogSeverity LOG_WARNING = 1;
162const LogSeverity LOG_ERROR = 2;
163const LogSeverity LOG_FATAL = 3;
164const LogSeverity LOG_NUM_SEVERITIES = 4;
165
166// LOG_DFATAL_LEVEL is LOG_FATAL in debug mode, ERROR in normal mode
167#ifdef NDEBUG
168const LogSeverity LOG_DFATAL_LEVEL = LOG_ERROR;
169#else
170const LogSeverity LOG_DFATAL_LEVEL = LOG_FATAL;
171#endif
172
173// A few definitions of macros that don't generate much code. These are used
174// by LOG() and LOG_IF, etc. Since these are used all over our code, it's
175// better to have compact code for these operations.
176#define COMPACT_GOOGLE_LOG_INFO \
177 logging::LogMessage(__FILE__, __LINE__)
178#define COMPACT_GOOGLE_LOG_WARNING \
179 logging::LogMessage(__FILE__, __LINE__, logging::LOG_WARNING)
180#define COMPACT_GOOGLE_LOG_ERROR \
181 logging::LogMessage(__FILE__, __LINE__, logging::LOG_ERROR)
182#define COMPACT_GOOGLE_LOG_FATAL \
183 logging::LogMessage(__FILE__, __LINE__, logging::LOG_FATAL)
184#define COMPACT_GOOGLE_LOG_DFATAL \
185 logging::LogMessage(__FILE__, __LINE__, logging::LOG_DFATAL_LEVEL)
186
187// wingdi.h defines ERROR to be 0. When we call LOG(ERROR), it gets
188// substituted with 0, and it expands to COMPACT_GOOGLE_LOG_0. To allow us
189// to keep using this syntax, we define this macro to do the same thing
190// as COMPACT_GOOGLE_LOG_ERROR, and also define ERROR the same way that
191// the Windows SDK does for consistency.
192#define ERROR 0
193#define COMPACT_GOOGLE_LOG_0 \
194 logging::LogMessage(__FILE__, __LINE__, logging::LOG_ERROR)
195
196// We use the preprocessor's merging operator, "##", so that, e.g.,
197// LOG(INFO) becomes the token COMPACT_GOOGLE_LOG_INFO. There's some funny
198// subtle difference between ostream member streaming functions (e.g.,
199// ostream::operator<<(int) and ostream non-member streaming functions
200// (e.g., ::operator<<(ostream&, string&): it turns out that it's
201// impossible to stream something like a string directly to an unnamed
202// ostream. We employ a neat hack by calling the stream() member
203// function of LogMessage which seems to avoid the problem.
204
205#define LOG(severity) COMPACT_GOOGLE_LOG_ ## severity.stream()
206#define SYSLOG(severity) LOG(severity)
207
208#define LOG_IF(severity, condition) \
209 !(condition) ? (void) 0 : logging::LogMessageVoidify() & LOG(severity)
210#define SYSLOG_IF(severity, condition) LOG_IF(severity, condition)
211
212#define LOG_ASSERT(condition) \
213 LOG_IF(FATAL, !(condition)) << "Assert failed: " #condition ". "
214#define SYSLOG_ASSERT(condition) \
215 SYSLOG_IF(FATAL, !(condition)) << "Assert failed: " #condition ". "
216
217// CHECK dies with a fatal error if condition is not true. It is *not*
218// controlled by NDEBUG, so the check will be executed regardless of
219// compilation mode.
220#define CHECK(condition) \
221 LOG_IF(FATAL, !(condition)) << "Check failed: " #condition ". "
222
223// A container for a string pointer which can be evaluated to a bool -
224// true iff the pointer is NULL.
225struct CheckOpString {
226 CheckOpString(std::string* str) : str_(str) { }
227 // No destructor: if str_ is non-NULL, we're about to LOG(FATAL),
228 // so there's no point in cleaning up str_.
229 operator bool() const { return str_ != NULL; }
230 std::string* str_;
231};
232
233// Build the error message string. This is separate from the "Impl"
234// function template because it is not performance critical and so can
235// be out of line, while the "Impl" code should be inline.
236template<class t1, class t2>
237std::string* MakeCheckOpString(const t1& v1, const t2& v2, const char* names) {
238 std::ostringstream ss;
239 ss << names << " (" << v1 << " vs. " << v2 << ")";
240 std::string* msg = new std::string(ss.str());
241 return msg;
242}
243
244extern std::string* MakeCheckOpStringIntInt(int v1, int v2, const char* names);
245
246template<int, int>
247std::string* MakeCheckOpString(const int& v1, const int& v2, const char* names) {
248 return MakeCheckOpStringIntInt(v1, v2, names);
249}
250
251// Plus some debug-logging macros that get compiled to nothing for production
252//
253// DEBUG_MODE is for uses like
254// if (DEBUG_MODE) foo.CheckThatFoo();
255// instead of
256// #ifndef NDEBUG
257// foo.CheckThatFoo();
258// #endif
259
260#ifndef NDEBUG
261
262#define DLOG(severity) LOG(severity)
263#define DLOG_IF(severity, condition) LOG_IF(severity, condition)
264#define DLOG_ASSERT(condition) LOG_ASSERT(condition)
265
266// debug-only checking. not executed in NDEBUG mode.
267enum { DEBUG_MODE = 1 };
268#define DCHECK(condition) \
269 LOG_IF(FATAL, !(condition)) << "Check failed: " #condition ". "
270
271// Helper macro for binary operators.
272// Don't use this macro directly in your code, use DCHECK_EQ et al below.
273#define DCHECK_OP(name, op, val1, val2) \
274 if (logging::CheckOpString _result = \
275 logging::Check##name##Impl((val1), (val2), #val1 " " #op " " #val2)) \
276 logging::LogMessage(__FILE__, __LINE__, _result).stream()
277
278// Helper functions for string comparisons.
279// To avoid bloat, the definitions are in logging.cc.
280#define DECLARE_DCHECK_STROP_IMPL(func, expected) \
281 std::string* Check##func##expected##Impl(const char* s1, \
282 const char* s2, \
283 const char* names);
284DECLARE_DCHECK_STROP_IMPL(strcmp, true)
285DECLARE_DCHECK_STROP_IMPL(strcmp, false)
286DECLARE_DCHECK_STROP_IMPL(_stricmp, true)
287DECLARE_DCHECK_STROP_IMPL(_stricmp, false)
288#undef DECLARE_DCHECK_STROP_IMPL
289
290// Helper macro for string comparisons.
291// Don't use this macro directly in your code, use CHECK_STREQ et al below.
292#define DCHECK_STROP(func, op, expected, s1, s2) \
293 while (CheckOpString _result = \
294 logging::Check##func##expected##Impl((s1), (s2), \
295 #s1 " " #op " " #s2)) \
296 LOG(FATAL) << *_result.str_
297
298// String (char*) equality/inequality checks.
299// CASE versions are case-insensitive.
300//
301// Note that "s1" and "s2" may be temporary strings which are destroyed
302// by the compiler at the end of the current "full expression"
303// (e.g. DCHECK_STREQ(Foo().c_str(), Bar().c_str())).
304
305#define DCHECK_STREQ(s1, s2) DCHECK_STROP(strcmp, ==, true, s1, s2)
306#define DCHECK_STRNE(s1, s2) DCHECK_STROP(strcmp, !=, false, s1, s2)
307#define DCHECK_STRCASEEQ(s1, s2) DCHECK_STROP(_stricmp, ==, true, s1, s2)
308#define DCHECK_STRCASENE(s1, s2) DCHECK_STROP(_stricmp, !=, false, s1, s2)
309
310#define DCHECK_INDEX(I,A) DCHECK(I < (sizeof(A)/sizeof(A[0])))
311#define DCHECK_BOUND(B,A) DCHECK(B <= (sizeof(A)/sizeof(A[0])))
312
313#else // NDEBUG
314
315#define DLOG(severity) \
316 true ? (void) 0 : logging::LogMessageVoidify() & LOG(severity)
317
318#define DLOG_IF(severity, condition) \
319 true ? (void) 0 : logging::LogMessageVoidify() & LOG(severity)
320
321#define DLOG_ASSERT(condition) \
322 true ? (void) 0 : LOG_ASSERT(condition)
323
324enum { DEBUG_MODE = 0 };
325
326// This macro can be followed by a sequence of stream parameters in
327// non-debug mode. The DCHECK and friends macros use this so that
328// the expanded expression DCHECK(foo) << "asdf" is still syntactically
329// valid, even though the expression will get optimized away.
330#define NDEBUG_EAT_STREAM_PARAMETERS \
331 logging::LogMessage(__FILE__, __LINE__).stream()
332
333// Set to true in InitLogging when we want to enable the dchecks in release.
334extern bool g_enable_dcheck;
335#define DCHECK(condition) \
336 !logging::g_enable_dcheck ? void (0) : \
337 LOG_IF(FATAL, !(condition)) << "Check failed: " #condition ". "
338
339// Helper macro for binary operators.
340// Don't use this macro directly in your code, use DCHECK_EQ et al below.
341#define DCHECK_OP(name, op, val1, val2) \
342 if (logging::g_enable_dcheck) \
343 if (logging::CheckOpString _result = \
344 logging::Check##name##Impl((val1), (val2), #val1 " " #op " " #val2)) \
345 logging::LogMessage(__FILE__, __LINE__, _result).stream()
346
347#define DCHECK_STREQ(str1, str2) \
348 while (false) NDEBUG_EAT_STREAM_PARAMETERS
349
350#define DCHECK_STRCASEEQ(str1, str2) \
351 while (false) NDEBUG_EAT_STREAM_PARAMETERS
352
353#define DCHECK_STRNE(str1, str2) \
354 while (false) NDEBUG_EAT_STREAM_PARAMETERS
355
356#define DCHECK_STRCASENE(str1, str2) \
357 while (false) NDEBUG_EAT_STREAM_PARAMETERS
358
359#endif // NDEBUG
360
361// Helper functions for DCHECK_OP macro.
362// The (int, int) specialization works around the issue that the compiler
363// will not instantiate the template version of the function on values of
364// unnamed enum type - see comment below.
365#define DEFINE_DCHECK_OP_IMPL(name, op) \
366 template <class t1, class t2> \
367 inline std::string* Check##name##Impl(const t1& v1, const t2& v2, \
368 const char* names) { \
369 if (v1 op v2) return NULL; \
370 else return MakeCheckOpString(v1, v2, names); \
371 } \
372 inline std::string* Check##name##Impl(int v1, int v2, const char* names) { \
373 if (v1 op v2) return NULL; \
374 else return MakeCheckOpString(v1, v2, names); \
375 }
376DEFINE_DCHECK_OP_IMPL(EQ, ==)
377DEFINE_DCHECK_OP_IMPL(NE, !=)
378DEFINE_DCHECK_OP_IMPL(LE, <=)
379DEFINE_DCHECK_OP_IMPL(LT, < )
380DEFINE_DCHECK_OP_IMPL(GE, >=)
381DEFINE_DCHECK_OP_IMPL(GT, > )
382#undef DEFINE_DCHECK_OP_IMPL
383
384// Equality/Inequality checks - compare two values, and log a LOG_FATAL message
385// including the two values when the result is not as expected. The values
386// must have operator<<(ostream, ...) defined.
387//
388// You may append to the error message like so:
389// DCHECK_NE(1, 2) << ": The world must be ending!";
390//
391// We are very careful to ensure that each argument is evaluated exactly
392// once, and that anything which is legal to pass as a function argument is
393// legal here. In particular, the arguments may be temporary expressions
394// which will end up being destroyed at the end of the apparent statement,
395// for example:
396// DCHECK_EQ(string("abc")[1], 'b');
397//
398// WARNING: These may not compile correctly if one of the arguments is a pointer
399// and the other is NULL. To work around this, simply static_cast NULL to the
400// type of the desired pointer.
401
402#define DCHECK_EQ(val1, val2) DCHECK_OP(EQ, ==, val1, val2)
403#define DCHECK_NE(val1, val2) DCHECK_OP(NE, !=, val1, val2)
404#define DCHECK_LE(val1, val2) DCHECK_OP(LE, <=, val1, val2)
405#define DCHECK_LT(val1, val2) DCHECK_OP(LT, < , val1, val2)
406#define DCHECK_GE(val1, val2) DCHECK_OP(GE, >=, val1, val2)
407#define DCHECK_GT(val1, val2) DCHECK_OP(GT, > , val1, val2)
408
409
410#define NOTREACHED() DCHECK(false)
411
412// Redefine the standard assert to use our nice log files
413#undef assert
414#define assert(x) DLOG_ASSERT(x)
415
416// This class more or less represents a particular log message. You
417// create an instance of LogMessage and then stream stuff to it.
418// When you finish streaming to it, ~LogMessage is called and the
419// full message gets streamed to the appropriate destination.
420//
421// You shouldn't actually use LogMessage's constructor to log things,
422// though. You should use the LOG() macro (and variants thereof)
423// above.
424class LogMessage {
425 public:
426 LogMessage(const char* file, int line, LogSeverity severity, int ctr);
427
428 // Two special constructors that generate reduced amounts of code at
429 // LOG call sites for common cases.
430 //
431 // Used for LOG(INFO): Implied are:
432 // severity = LOG_INFO, ctr = 0
433 //
434 // Using this constructor instead of the more complex constructor above
435 // saves a couple of bytes per call site.
436 LogMessage(const char* file, int line);
437
438 // Used for LOG(severity) where severity != INFO. Implied
439 // are: ctr = 0
440 //
441 // Using this constructor instead of the more complex constructor above
442 // saves a couple of bytes per call site.
443 LogMessage(const char* file, int line, LogSeverity severity);
444
445 // A special constructor used for check failures.
446 // Implied severity = LOG_FATAL
447 LogMessage(const char* file, int line, const CheckOpString& result);
448
449 ~LogMessage();
450
451 std::ostream& stream() { return stream_; }
452
453 private:
454 void Init(const char* file, int line);
455
456 LogSeverity severity_;
457 std::ostringstream stream_;
maruel@google.coma855b0f2008-07-30 22:02:03 +0900458 size_t message_start_; // Offset of the start of the message (past prefix
459 // info).
initial.commit3f4a7322008-07-27 06:49:38 +0900460
brettw@google.come3c034a2008-08-08 03:31:40 +0900461 DISALLOW_COPY_AND_ASSIGN(LogMessage);
initial.commit3f4a7322008-07-27 06:49:38 +0900462};
463
464// A non-macro interface to the log facility; (useful
465// when the logging level is not a compile-time constant).
466inline void LogAtLevel(int const log_level, std::string const &msg) {
467 LogMessage(__FILE__, __LINE__, log_level).stream() << msg;
468}
469
470// This class is used to explicitly ignore values in the conditional
471// logging macros. This avoids compiler warnings like "value computed
472// is not used" and "statement has no effect".
473class LogMessageVoidify {
474 public:
475 LogMessageVoidify() { }
476 // This has to be an operator with a precedence lower than << but
477 // higher than ?:
478 void operator&(std::ostream&) { }
479};
480
481// Closes the log file explicitly if open.
482// NOTE: Since the log file is opened as necessary by the action of logging
483// statements, there's no guarantee that it will stay closed
484// after this call.
485void CloseLogFile();
486
brettw@google.come3c034a2008-08-08 03:31:40 +0900487} // namespace logging
initial.commit3f4a7322008-07-27 06:49:38 +0900488
489// These functions are provided as a convenience for logging, which is where we
490// use streams (it is against Google style to use streams in other places). It
491// is designed to allow you to emit non-ASCII Unicode strings to the log file,
492// which is normally ASCII. It is relatively slow, so try not to use it for
brettw@google.come3c034a2008-08-08 03:31:40 +0900493// common cases. Non-ASCII characters will be converted to UTF-8 by these
494// operators.
initial.commit3f4a7322008-07-27 06:49:38 +0900495std::ostream& operator<<(std::ostream& out, const wchar_t* wstr);
496inline std::ostream& operator<<(std::ostream& out, const std::wstring& wstr) {
497 return out << wstr.c_str();
498}
499
brettw@google.come3c034a2008-08-08 03:31:40 +0900500#endif // BASE_LOGGING_H_
license.botf003cfe2008-08-24 09:55:55 +0900501