blob: 662deae115bf9eaa6af4e91b75ab4e6ab96742ae [file] [log] [blame]
erg@google.comd5fffd42011-01-08 03:06:45 +09001// Copyright (c) 2011 The Chromium Authors. All rights reserved.
license.botf003cfe2008-08-24 09:55:55 +09002// 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_
thakis@chromium.org01d14522010-07-27 08:08:24 +09007#pragma once
initial.commit3f4a7322008-07-27 06:49:38 +09008
9#include <string>
10#include <cstring>
11#include <sstream>
12
13#include "base/basictypes.h"
initial.commit3f4a7322008-07-27 06:49:38 +090014
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//
akalin@chromium.orgf0ee79c2010-09-30 04:26:36 +090077// There are "verbose level" logging macros. They look like
78//
79// VLOG(1) << "I'm printed when you run the program with --v=1 or more";
80// VLOG(2) << "I'm printed when you run the program with --v=2 or more";
81//
82// These always log at the INFO log level (when they log at all).
83// The verbose logging can also be turned on module-by-module. For instance,
akalin@chromium.org859d7d42010-10-29 09:39:48 +090084// --vmodule=profile=2,icon_loader=1,browser_*=3,*/chromeos/*=4 --v=0
akalin@chromium.orgf0ee79c2010-09-30 04:26:36 +090085// will cause:
86// a. VLOG(2) and lower messages to be printed from profile.{h,cc}
87// b. VLOG(1) and lower messages to be printed from icon_loader.{h,cc}
88// c. VLOG(3) and lower messages to be printed from files prefixed with
89// "browser"
akalin@chromium.org55a8a812010-11-02 05:50:55 +090090// d. VLOG(4) and lower messages to be printed from files under a
akalin@chromium.org859d7d42010-10-29 09:39:48 +090091// "chromeos" directory.
akalin@chromium.org55a8a812010-11-02 05:50:55 +090092// e. VLOG(0) and lower messages to be printed from elsewhere
akalin@chromium.orgf0ee79c2010-09-30 04:26:36 +090093//
94// The wildcarding functionality shown by (c) supports both '*' (match
akalin@chromium.org859d7d42010-10-29 09:39:48 +090095// 0 or more characters) and '?' (match any single character)
96// wildcards. Any pattern containing a forward or backward slash will
97// be tested against the whole pathname and not just the module.
98// E.g., "*/foo/bar/*=2" would change the logging level for all code
99// in source files under a "foo/bar" directory.
akalin@chromium.orgf0ee79c2010-09-30 04:26:36 +0900100//
101// There's also VLOG_IS_ON(n) "verbose level" condition macro. To be used as
102//
103// if (VLOG_IS_ON(2)) {
104// // do some logging preparation and logging
105// // that can't be accomplished with just VLOG(2) << ...;
106// }
107//
108// There is also a VLOG_IF "verbose level" condition macro for sample
109// cases, when some extra computation and preparation for logs is not
110// needed.
111//
112// VLOG_IF(1, (size > 1024))
113// << "I'm printed when size is more than 1024 and when you run the "
114// "program with --v=1 or more";
115//
initial.commit3f4a7322008-07-27 06:49:38 +0900116// We also override the standard 'assert' to use 'DLOG_ASSERT'.
117//
tschmelcher@chromium.orgf29a4fc2009-10-10 08:52:20 +0900118// Lastly, there is:
119//
120// PLOG(ERROR) << "Couldn't do foo";
121// DPLOG(ERROR) << "Couldn't do foo";
122// PLOG_IF(ERROR, cond) << "Couldn't do foo";
123// DPLOG_IF(ERROR, cond) << "Couldn't do foo";
124// PCHECK(condition) << "Couldn't do foo";
125// DPCHECK(condition) << "Couldn't do foo";
126//
127// which append the last system error to the message in string form (taken from
128// GetLastError() on Windows and errno on POSIX).
129//
initial.commit3f4a7322008-07-27 06:49:38 +0900130// The supported severity levels for macros that allow you to specify one
huanr@chromium.org656253e2009-02-12 10:19:05 +0900131// are (in increasing order of severity) INFO, WARNING, ERROR, ERROR_REPORT,
132// and FATAL.
initial.commit3f4a7322008-07-27 06:49:38 +0900133//
134// Very important: logging a message at the FATAL severity level causes
135// the program to terminate (after the message is logged).
huanr@chromium.org656253e2009-02-12 10:19:05 +0900136//
137// Note the special severity of ERROR_REPORT only available/relevant in normal
138// mode, which displays error dialog without terminating the program. There is
139// no error dialog for severity ERROR or below in normal mode.
140//
141// There is also the special severity of DFATAL, which logs FATAL in
jar@chromium.orgac61a722010-06-24 10:01:04 +0900142// debug mode, ERROR in normal mode.
initial.commit3f4a7322008-07-27 06:49:38 +0900143
144namespace logging {
145
146// Where to record logging output? A flat file and/or system debug log via
evanm@google.com4eb4f372008-11-18 09:59:04 +0900147// OutputDebugString. Defaults on Windows to LOG_ONLY_TO_FILE, and on
148// POSIX to LOG_ONLY_TO_SYSTEM_DEBUG_LOG (aka stderr).
initial.commit3f4a7322008-07-27 06:49:38 +0900149enum LoggingDestination { LOG_NONE,
150 LOG_ONLY_TO_FILE,
151 LOG_ONLY_TO_SYSTEM_DEBUG_LOG,
152 LOG_TO_BOTH_FILE_AND_SYSTEM_DEBUG_LOG };
153
154// Indicates that the log file should be locked when being written to.
155// Often, there is no locking, which is fine for a single threaded program.
156// If logging is being done from multiple threads or there can be more than
157// one process doing the logging, the file should be locked during writes to
158// make each log outut atomic. Other writers will block.
159//
160// All processes writing to the log file must have their locking set for it to
161// work properly. Defaults to DONT_LOCK_LOG_FILE.
162enum LogLockingState { LOCK_LOG_FILE, DONT_LOCK_LOG_FILE };
163
164// On startup, should we delete or append to an existing log file (if any)?
165// Defaults to APPEND_TO_OLD_LOG_FILE.
166enum OldFileDeletionState { DELETE_OLD_LOG_FILE, APPEND_TO_OLD_LOG_FILE };
167
akalin@chromium.orgfaed5f82011-01-11 10:03:36 +0900168enum DcheckState {
169 DISABLE_DCHECK_FOR_NON_OFFICIAL_RELEASE_BUILDS,
170 ENABLE_DCHECK_FOR_NON_OFFICIAL_RELEASE_BUILDS
171};
172
derat@chromium.orgb2aa7c42010-08-24 04:57:46 +0900173// TODO(avi): do we want to do a unification of character types here?
174#if defined(OS_WIN)
175typedef wchar_t PathChar;
176#else
177typedef char PathChar;
178#endif
179
180// Define different names for the BaseInitLoggingImpl() function depending on
181// whether NDEBUG is defined or not so that we'll fail to link if someone tries
182// to compile logging.cc with NDEBUG but includes logging.h without defining it,
183// or vice versa.
184#if NDEBUG
185#define BaseInitLoggingImpl BaseInitLoggingImpl_built_with_NDEBUG
186#else
187#define BaseInitLoggingImpl BaseInitLoggingImpl_built_without_NDEBUG
188#endif
189
190// Implementation of the InitLogging() method declared below. We use a
191// more-specific name so we can #define it above without affecting other code
192// that has named stuff "InitLogging".
gspencer@chromium.org49c808a2010-10-28 09:20:21 +0900193bool BaseInitLoggingImpl(const PathChar* log_file,
derat@chromium.orgb2aa7c42010-08-24 04:57:46 +0900194 LoggingDestination logging_dest,
195 LogLockingState lock_log,
akalin@chromium.orgfaed5f82011-01-11 10:03:36 +0900196 OldFileDeletionState delete_old,
197 DcheckState dcheck_state);
derat@chromium.orgb2aa7c42010-08-24 04:57:46 +0900198
initial.commit3f4a7322008-07-27 06:49:38 +0900199// Sets the log file name and other global logging state. Calling this function
200// is recommended, and is normally done at the beginning of application init.
201// If you don't call it, all the flags will be initialized to their default
202// values, and there is a race condition that may leak a critical section
203// object if two threads try to do the first log at the same time.
204// See the definition of the enums above for descriptions and default values.
205//
206// The default log file is initialized to "debug.log" in the application
207// directory. You probably don't want this, especially since the program
208// directory may not be writable on an enduser's system.
gspencer@chromium.org49c808a2010-10-28 09:20:21 +0900209inline bool InitLogging(const PathChar* log_file,
derat@chromium.orgb2aa7c42010-08-24 04:57:46 +0900210 LoggingDestination logging_dest,
211 LogLockingState lock_log,
akalin@chromium.orgfaed5f82011-01-11 10:03:36 +0900212 OldFileDeletionState delete_old,
213 DcheckState dcheck_state) {
214 return BaseInitLoggingImpl(log_file, logging_dest, lock_log,
215 delete_old, dcheck_state);
derat@chromium.orgb2aa7c42010-08-24 04:57:46 +0900216}
initial.commit3f4a7322008-07-27 06:49:38 +0900217
218// Sets the log level. Anything at or above this level will be written to the
219// log file/displayed to the user (if applicable). Anything below this level
siggi@chromium.org25396e12010-11-05 00:50:49 +0900220// will be silently ignored. The log level defaults to 0 (everything is logged
221// up to level INFO) if this function is not called.
222// Note that log messages for VLOG(x) are logged at level -x, so setting
223// the min log level to negative values enables verbose logging.
initial.commit3f4a7322008-07-27 06:49:38 +0900224void SetMinLogLevel(int level);
225
ericroman@google.com38450852009-04-11 04:13:42 +0900226// Gets the current log level.
initial.commit3f4a7322008-07-27 06:49:38 +0900227int GetMinLogLevel();
228
siggi@chromium.org25396e12010-11-05 00:50:49 +0900229// Gets the VLOG default verbosity level.
230int GetVlogVerbosity();
231
akalin@chromium.orgf0ee79c2010-09-30 04:26:36 +0900232// Gets the current vlog level for the given file (usually taken from
233// __FILE__).
akalin@chromium.org59c9f212010-09-30 06:25:14 +0900234
235// Note that |N| is the size *with* the null terminator.
236int GetVlogLevelHelper(const char* file_start, size_t N);
237
akalin@chromium.orgf0ee79c2010-09-30 04:26:36 +0900238template <size_t N>
239int GetVlogLevel(const char (&file)[N]) {
240 return GetVlogLevelHelper(file, N);
241}
initial.commit3f4a7322008-07-27 06:49:38 +0900242
243// Sets the common items you want to be prepended to each log message.
244// process and thread IDs default to off, the timestamp defaults to on.
245// If this function is not called, logging defaults to writing the timestamp
246// only.
247void SetLogItems(bool enable_process_id, bool enable_thread_id,
248 bool enable_timestamp, bool enable_tickcount);
249
cmasone@google.comf7802482010-08-17 09:38:12 +0900250// Sets whether or not you'd like to see fatal debug messages popped up in
251// a dialog box or not.
252// Dialogs are not shown by default.
253void SetShowErrorDialogs(bool enable_dialogs);
254
initial.commit3f4a7322008-07-27 06:49:38 +0900255// Sets the Log Assert Handler that will be used to notify of check failures.
huanr@chromium.org656253e2009-02-12 10:19:05 +0900256// The default handler shows a dialog box and then terminate the process,
257// however clients can use this function to override with their own handling
258// (e.g. a silent one for Unit Tests)
initial.commit3f4a7322008-07-27 06:49:38 +0900259typedef void (*LogAssertHandlerFunction)(const std::string& str);
260void SetLogAssertHandler(LogAssertHandlerFunction handler);
hansl@google.com519197c2010-11-04 04:20:27 +0900261
huanr@chromium.org656253e2009-02-12 10:19:05 +0900262// Sets the Log Report Handler that will be used to notify of check failures
263// in non-debug mode. The default handler shows a dialog box and continues
264// the execution, however clients can use this function to override with their
265// own handling.
266typedef void (*LogReportHandlerFunction)(const std::string& str);
267void SetLogReportHandler(LogReportHandlerFunction handler);
initial.commit3f4a7322008-07-27 06:49:38 +0900268
siggi@chromium.org4db65792009-11-26 00:26:34 +0900269// Sets the Log Message Handler that gets passed every log message before
270// it's sent to other log destinations (if any).
271// Returns true to signal that it handled the message and the message
272// should not be sent to other log destinations.
siggi@chromium.org25396e12010-11-05 00:50:49 +0900273typedef bool (*LogMessageHandlerFunction)(int severity,
274 const char* file, int line, size_t message_start, const std::string& str);
siggi@chromium.org4db65792009-11-26 00:26:34 +0900275void SetLogMessageHandler(LogMessageHandlerFunction handler);
hansl@google.com519197c2010-11-04 04:20:27 +0900276LogMessageHandlerFunction GetLogMessageHandler();
siggi@chromium.org4db65792009-11-26 00:26:34 +0900277
initial.commit3f4a7322008-07-27 06:49:38 +0900278typedef int LogSeverity;
siggi@chromium.org25396e12010-11-05 00:50:49 +0900279const LogSeverity LOG_VERBOSE = -1; // This is level 1 verbosity
280// Note: the log severities are used to index into the array of names,
281// see log_severity_names.
initial.commit3f4a7322008-07-27 06:49:38 +0900282const LogSeverity LOG_INFO = 0;
283const LogSeverity LOG_WARNING = 1;
284const LogSeverity LOG_ERROR = 2;
huanr@chromium.org656253e2009-02-12 10:19:05 +0900285const LogSeverity LOG_ERROR_REPORT = 3;
286const LogSeverity LOG_FATAL = 4;
287const LogSeverity LOG_NUM_SEVERITIES = 5;
initial.commit3f4a7322008-07-27 06:49:38 +0900288
akalin@chromium.orga88579b2010-10-02 08:02:36 +0900289// LOG_DFATAL is LOG_FATAL in debug mode, ERROR in normal mode
initial.commit3f4a7322008-07-27 06:49:38 +0900290#ifdef NDEBUG
akalin@chromium.orga88579b2010-10-02 08:02:36 +0900291const LogSeverity LOG_DFATAL = LOG_ERROR;
initial.commit3f4a7322008-07-27 06:49:38 +0900292#else
akalin@chromium.orga88579b2010-10-02 08:02:36 +0900293const LogSeverity LOG_DFATAL = LOG_FATAL;
initial.commit3f4a7322008-07-27 06:49:38 +0900294#endif
295
296// A few definitions of macros that don't generate much code. These are used
297// by LOG() and LOG_IF, etc. Since these are used all over our code, it's
298// better to have compact code for these operations.
tschmelcher@chromium.orgf29a4fc2009-10-10 08:52:20 +0900299#define COMPACT_GOOGLE_LOG_EX_INFO(ClassName, ...) \
300 logging::ClassName(__FILE__, __LINE__, logging::LOG_INFO , ##__VA_ARGS__)
301#define COMPACT_GOOGLE_LOG_EX_WARNING(ClassName, ...) \
302 logging::ClassName(__FILE__, __LINE__, logging::LOG_WARNING , ##__VA_ARGS__)
303#define COMPACT_GOOGLE_LOG_EX_ERROR(ClassName, ...) \
304 logging::ClassName(__FILE__, __LINE__, logging::LOG_ERROR , ##__VA_ARGS__)
305#define COMPACT_GOOGLE_LOG_EX_ERROR_REPORT(ClassName, ...) \
306 logging::ClassName(__FILE__, __LINE__, \
307 logging::LOG_ERROR_REPORT , ##__VA_ARGS__)
308#define COMPACT_GOOGLE_LOG_EX_FATAL(ClassName, ...) \
309 logging::ClassName(__FILE__, __LINE__, logging::LOG_FATAL , ##__VA_ARGS__)
310#define COMPACT_GOOGLE_LOG_EX_DFATAL(ClassName, ...) \
akalin@chromium.orga88579b2010-10-02 08:02:36 +0900311 logging::ClassName(__FILE__, __LINE__, logging::LOG_DFATAL , ##__VA_ARGS__)
tschmelcher@chromium.orgf29a4fc2009-10-10 08:52:20 +0900312
initial.commit3f4a7322008-07-27 06:49:38 +0900313#define COMPACT_GOOGLE_LOG_INFO \
tschmelcher@chromium.orgf29a4fc2009-10-10 08:52:20 +0900314 COMPACT_GOOGLE_LOG_EX_INFO(LogMessage)
initial.commit3f4a7322008-07-27 06:49:38 +0900315#define COMPACT_GOOGLE_LOG_WARNING \
tschmelcher@chromium.orgf29a4fc2009-10-10 08:52:20 +0900316 COMPACT_GOOGLE_LOG_EX_WARNING(LogMessage)
initial.commit3f4a7322008-07-27 06:49:38 +0900317#define COMPACT_GOOGLE_LOG_ERROR \
tschmelcher@chromium.orgf29a4fc2009-10-10 08:52:20 +0900318 COMPACT_GOOGLE_LOG_EX_ERROR(LogMessage)
huanr@chromium.org656253e2009-02-12 10:19:05 +0900319#define COMPACT_GOOGLE_LOG_ERROR_REPORT \
tschmelcher@chromium.orgf29a4fc2009-10-10 08:52:20 +0900320 COMPACT_GOOGLE_LOG_EX_ERROR_REPORT(LogMessage)
initial.commit3f4a7322008-07-27 06:49:38 +0900321#define COMPACT_GOOGLE_LOG_FATAL \
tschmelcher@chromium.orgf29a4fc2009-10-10 08:52:20 +0900322 COMPACT_GOOGLE_LOG_EX_FATAL(LogMessage)
initial.commit3f4a7322008-07-27 06:49:38 +0900323#define COMPACT_GOOGLE_LOG_DFATAL \
tschmelcher@chromium.orgf29a4fc2009-10-10 08:52:20 +0900324 COMPACT_GOOGLE_LOG_EX_DFATAL(LogMessage)
initial.commit3f4a7322008-07-27 06:49:38 +0900325
326// wingdi.h defines ERROR to be 0. When we call LOG(ERROR), it gets
327// substituted with 0, and it expands to COMPACT_GOOGLE_LOG_0. To allow us
328// to keep using this syntax, we define this macro to do the same thing
329// as COMPACT_GOOGLE_LOG_ERROR, and also define ERROR the same way that
330// the Windows SDK does for consistency.
331#define ERROR 0
tschmelcher@chromium.orgf29a4fc2009-10-10 08:52:20 +0900332#define COMPACT_GOOGLE_LOG_EX_0(ClassName, ...) \
333 COMPACT_GOOGLE_LOG_EX_ERROR(ClassName , ##__VA_ARGS__)
334#define COMPACT_GOOGLE_LOG_0 COMPACT_GOOGLE_LOG_ERROR
akalin@chromium.orga88579b2010-10-02 08:02:36 +0900335// Needed for LOG_IS_ON(ERROR).
336const LogSeverity LOG_0 = LOG_ERROR;
337
akalin@chromium.org434c5b62010-11-03 14:30:14 +0900338// As special cases, we can assume that LOG_IS_ON(ERROR_REPORT) and
339// LOG_IS_ON(FATAL) always hold. Also, LOG_IS_ON(DFATAL) always holds
340// in debug mode. In particular, CHECK()s will always fire if they
341// fail.
akalin@chromium.orga88579b2010-10-02 08:02:36 +0900342#define LOG_IS_ON(severity) \
343 ((::logging::LOG_ ## severity) >= ::logging::GetMinLogLevel())
344
345// We can't do any caching tricks with VLOG_IS_ON() like the
346// google-glog version since it requires GCC extensions. This means
347// that using the v-logging functions in conjunction with --vmodule
348// may be slow.
349#define VLOG_IS_ON(verboselevel) \
350 ((verboselevel) <= ::logging::GetVlogLevel(__FILE__))
351
352// Helper macro which avoids evaluating the arguments to a stream if
353// the condition doesn't hold.
354#define LAZY_STREAM(stream, condition) \
355 !(condition) ? (void) 0 : ::logging::LogMessageVoidify() & (stream)
initial.commit3f4a7322008-07-27 06:49:38 +0900356
357// We use the preprocessor's merging operator, "##", so that, e.g.,
358// LOG(INFO) becomes the token COMPACT_GOOGLE_LOG_INFO. There's some funny
359// subtle difference between ostream member streaming functions (e.g.,
360// ostream::operator<<(int) and ostream non-member streaming functions
361// (e.g., ::operator<<(ostream&, string&): it turns out that it's
362// impossible to stream something like a string directly to an unnamed
363// ostream. We employ a neat hack by calling the stream() member
364// function of LogMessage which seems to avoid the problem.
akalin@chromium.orga88579b2010-10-02 08:02:36 +0900365#define LOG_STREAM(severity) COMPACT_GOOGLE_LOG_ ## severity.stream()
initial.commit3f4a7322008-07-27 06:49:38 +0900366
akalin@chromium.orga88579b2010-10-02 08:02:36 +0900367#define LOG(severity) LAZY_STREAM(LOG_STREAM(severity), LOG_IS_ON(severity))
368#define LOG_IF(severity, condition) \
369 LAZY_STREAM(LOG_STREAM(severity), LOG_IS_ON(severity) && (condition))
370
initial.commit3f4a7322008-07-27 06:49:38 +0900371#define SYSLOG(severity) LOG(severity)
akalin@chromium.orga88579b2010-10-02 08:02:36 +0900372#define SYSLOG_IF(severity, condition) LOG_IF(severity, condition)
373
siggi@chromium.org25396e12010-11-05 00:50:49 +0900374// The VLOG macros log with negative verbosities.
375#define VLOG_STREAM(verbose_level) \
376 logging::LogMessage(__FILE__, __LINE__, -verbose_level).stream()
377
378#define VLOG(verbose_level) \
379 LAZY_STREAM(VLOG_STREAM(verbose_level), VLOG_IS_ON(verbose_level))
380
381#define VLOG_IF(verbose_level, condition) \
382 LAZY_STREAM(VLOG_STREAM(verbose_level), \
383 VLOG_IS_ON(verbose_level) && (condition))
akalin@chromium.orgf0ee79c2010-09-30 04:26:36 +0900384
385// TODO(akalin): Add more VLOG variants, e.g. VPLOG.
initial.commit3f4a7322008-07-27 06:49:38 +0900386
initial.commit3f4a7322008-07-27 06:49:38 +0900387#define LOG_ASSERT(condition) \
388 LOG_IF(FATAL, !(condition)) << "Assert failed: " #condition ". "
389#define SYSLOG_ASSERT(condition) \
390 SYSLOG_IF(FATAL, !(condition)) << "Assert failed: " #condition ". "
391
tschmelcher@chromium.orgf29a4fc2009-10-10 08:52:20 +0900392#if defined(OS_WIN)
akalin@chromium.orga88579b2010-10-02 08:02:36 +0900393#define LOG_GETLASTERROR_STREAM(severity) \
tschmelcher@chromium.orgf29a4fc2009-10-10 08:52:20 +0900394 COMPACT_GOOGLE_LOG_EX_ ## severity(Win32ErrorLogMessage, \
395 ::logging::GetLastSystemErrorCode()).stream()
akalin@chromium.orga88579b2010-10-02 08:02:36 +0900396#define LOG_GETLASTERROR(severity) \
397 LAZY_STREAM(LOG_GETLASTERROR_STREAM(severity), LOG_IS_ON(severity))
398#define LOG_GETLASTERROR_MODULE_STREAM(severity, module) \
tschmelcher@chromium.orgf29a4fc2009-10-10 08:52:20 +0900399 COMPACT_GOOGLE_LOG_EX_ ## severity(Win32ErrorLogMessage, \
400 ::logging::GetLastSystemErrorCode(), module).stream()
akalin@chromium.orga88579b2010-10-02 08:02:36 +0900401#define LOG_GETLASTERROR_MODULE(severity, module) \
402 LAZY_STREAM(LOG_GETLASTERROR_STREAM(severity, module), \
403 LOG_IS_ON(severity))
404// PLOG_STREAM is used by PLOG, which is the usual error logging macro
405// for each platform.
406#define PLOG_STREAM(severity) LOG_GETLASTERROR_STREAM(severity)
tschmelcher@chromium.orgf29a4fc2009-10-10 08:52:20 +0900407#elif defined(OS_POSIX)
akalin@chromium.orga88579b2010-10-02 08:02:36 +0900408#define LOG_ERRNO_STREAM(severity) \
tschmelcher@chromium.orgf29a4fc2009-10-10 08:52:20 +0900409 COMPACT_GOOGLE_LOG_EX_ ## severity(ErrnoLogMessage, \
410 ::logging::GetLastSystemErrorCode()).stream()
akalin@chromium.orga88579b2010-10-02 08:02:36 +0900411#define LOG_ERRNO(severity) \
412 LAZY_STREAM(LOG_ERRNO_STREAM(severity), LOG_IS_ON(severity))
413// PLOG_STREAM is used by PLOG, which is the usual error logging macro
414// for each platform.
415#define PLOG_STREAM(severity) LOG_ERRNO_STREAM(severity)
tschmelcher@chromium.orgf29a4fc2009-10-10 08:52:20 +0900416// TODO(tschmelcher): Should we add OSStatus logging for Mac?
417#endif
418
akalin@chromium.orga88579b2010-10-02 08:02:36 +0900419#define PLOG(severity) \
420 LAZY_STREAM(PLOG_STREAM(severity), LOG_IS_ON(severity))
421
tschmelcher@chromium.orgf29a4fc2009-10-10 08:52:20 +0900422#define PLOG_IF(severity, condition) \
akalin@chromium.orga88579b2010-10-02 08:02:36 +0900423 LAZY_STREAM(PLOG_STREAM(severity), LOG_IS_ON(severity) && (condition))
tschmelcher@chromium.orgf29a4fc2009-10-10 08:52:20 +0900424
initial.commit3f4a7322008-07-27 06:49:38 +0900425// CHECK dies with a fatal error if condition is not true. It is *not*
426// controlled by NDEBUG, so the check will be executed regardless of
427// compilation mode.
akalin@chromium.orga88579b2010-10-02 08:02:36 +0900428//
429// We make sure CHECK et al. always evaluates their arguments, as
430// doing CHECK(FunctionWithSideEffect()) is a common idiom.
akalin@chromium.orga88579b2010-10-02 08:02:36 +0900431#define CHECK(condition) \
432 LAZY_STREAM(LOG_STREAM(FATAL), !(condition)) \
433 << "Check failed: " #condition ". "
initial.commit3f4a7322008-07-27 06:49:38 +0900434
tschmelcher@chromium.orgf29a4fc2009-10-10 08:52:20 +0900435#define PCHECK(condition) \
akalin@chromium.orga88579b2010-10-02 08:02:36 +0900436 LAZY_STREAM(PLOG_STREAM(FATAL), !(condition)) \
437 << "Check failed: " #condition ". "
tschmelcher@chromium.orgf29a4fc2009-10-10 08:52:20 +0900438
initial.commit3f4a7322008-07-27 06:49:38 +0900439// A container for a string pointer which can be evaluated to a bool -
440// true iff the pointer is NULL.
441struct CheckOpString {
442 CheckOpString(std::string* str) : str_(str) { }
443 // No destructor: if str_ is non-NULL, we're about to LOG(FATAL),
444 // so there's no point in cleaning up str_.
445 operator bool() const { return str_ != NULL; }
446 std::string* str_;
447};
448
449// Build the error message string. This is separate from the "Impl"
450// function template because it is not performance critical and so can
451// be out of line, while the "Impl" code should be inline.
452template<class t1, class t2>
453std::string* MakeCheckOpString(const t1& v1, const t2& v2, const char* names) {
454 std::ostringstream ss;
455 ss << names << " (" << v1 << " vs. " << v2 << ")";
456 std::string* msg = new std::string(ss.str());
457 return msg;
458}
459
erg@google.com6575f362010-10-01 04:10:03 +0900460// MSVC doesn't like complex extern templates and DLLs.
461#if !defined(COMPILER_MSVC)
462// Commonly used instantiations of MakeCheckOpString<>. Explicitly instantiated
463// in logging.cc.
464extern template std::string* MakeCheckOpString<int, int>(
465 const int&, const int&, const char* names);
466extern template std::string* MakeCheckOpString<unsigned long, unsigned long>(
467 const unsigned long&, const unsigned long&, const char* names);
468extern template std::string* MakeCheckOpString<unsigned long, unsigned int>(
469 const unsigned long&, const unsigned int&, const char* names);
470extern template std::string* MakeCheckOpString<unsigned int, unsigned long>(
471 const unsigned int&, const unsigned long&, const char* names);
472extern template std::string* MakeCheckOpString<std::string, std::string>(
473 const std::string&, const std::string&, const char* name);
474#endif
initial.commit3f4a7322008-07-27 06:49:38 +0900475
willchan@chromium.orge5ec8202010-03-02 09:41:12 +0900476// Helper macro for binary operators.
477// Don't use this macro directly in your code, use CHECK_EQ et al below.
akalin@chromium.orga88579b2010-10-02 08:02:36 +0900478//
479// TODO(akalin): Rewrite this so that constructs like if (...)
480// CHECK_EQ(...) else { ... } work properly.
481#define CHECK_OP(name, op, val1, val2) \
482 if (logging::CheckOpString _result = \
483 logging::Check##name##Impl((val1), (val2), \
484 #val1 " " #op " " #val2)) \
akalin@chromium.orgbb884042010-10-01 07:38:30 +0900485 logging::LogMessage(__FILE__, __LINE__, _result).stream()
willchan@chromium.orge5ec8202010-03-02 09:41:12 +0900486
akalin@chromium.orgad6c1722010-11-02 07:19:56 +0900487// Helper functions for CHECK_OP macro.
488// The (int, int) specialization works around the issue that the compiler
489// will not instantiate the template version of the function on values of
490// unnamed enum type - see comment below.
491#define DEFINE_CHECK_OP_IMPL(name, op) \
492 template <class t1, class t2> \
493 inline std::string* Check##name##Impl(const t1& v1, const t2& v2, \
494 const char* names) { \
495 if (v1 op v2) return NULL; \
496 else return MakeCheckOpString(v1, v2, names); \
497 } \
498 inline std::string* Check##name##Impl(int v1, int v2, const char* names) { \
499 if (v1 op v2) return NULL; \
500 else return MakeCheckOpString(v1, v2, names); \
501 }
502DEFINE_CHECK_OP_IMPL(EQ, ==)
503DEFINE_CHECK_OP_IMPL(NE, !=)
504DEFINE_CHECK_OP_IMPL(LE, <=)
505DEFINE_CHECK_OP_IMPL(LT, < )
506DEFINE_CHECK_OP_IMPL(GE, >=)
507DEFINE_CHECK_OP_IMPL(GT, > )
508#undef DEFINE_CHECK_OP_IMPL
willchan@chromium.orge5ec8202010-03-02 09:41:12 +0900509
510#define CHECK_EQ(val1, val2) CHECK_OP(EQ, ==, val1, val2)
511#define CHECK_NE(val1, val2) CHECK_OP(NE, !=, val1, val2)
512#define CHECK_LE(val1, val2) CHECK_OP(LE, <=, val1, val2)
513#define CHECK_LT(val1, val2) CHECK_OP(LT, < , val1, val2)
514#define CHECK_GE(val1, val2) CHECK_OP(GE, >=, val1, val2)
515#define CHECK_GT(val1, val2) CHECK_OP(GT, > , val1, val2)
516
mark@chromium.org667f6212009-08-20 10:20:29 +0900517// http://crbug.com/16512 is open for a real fix for this. For now, Windows
518// uses OFFICIAL_BUILD and other platforms use the branding flag when NDEBUG is
519// defined.
520#if ( defined(OS_WIN) && defined(OFFICIAL_BUILD)) || \
521 (!defined(OS_WIN) && defined(NDEBUG) && defined(GOOGLE_CHROME_BUILD))
akalin@chromium.orga88579b2010-10-02 08:02:36 +0900522// Used by unit tests.
523#define LOGGING_IS_OFFICIAL_BUILD
524
mark@chromium.org667f6212009-08-20 10:20:29 +0900525// In order to have optimized code for official builds, remove DLOGs and
526// DCHECKs.
akalin@chromium.org85510482010-10-01 06:12:33 +0900527#define ENABLE_DLOG 0
528#define ENABLE_DCHECK 0
529
530#elif defined(NDEBUG)
531// Otherwise, if we're a release build, remove DLOGs but not DCHECKs
532// (since those can still be turned on via a command-line flag).
533#define ENABLE_DLOG 0
534#define ENABLE_DCHECK 1
535
536#else
537// Otherwise, we're a debug build so enable DLOGs and DCHECKs.
538#define ENABLE_DLOG 1
539#define ENABLE_DCHECK 1
mark@chromium.org667f6212009-08-20 10:20:29 +0900540#endif
541
akalin@chromium.org85510482010-10-01 06:12:33 +0900542// Definitions for DLOG et al.
543
akalin@chromium.orgf6b59fa2010-10-01 11:58:24 +0900544#if ENABLE_DLOG
545
akalin@chromium.org25cef532010-11-02 04:49:22 +0900546#define DLOG_IS_ON(severity) LOG_IS_ON(severity)
akalin@chromium.orgf6b59fa2010-10-01 11:58:24 +0900547#define DLOG_IF(severity, condition) LOG_IF(severity, condition)
548#define DLOG_ASSERT(condition) LOG_ASSERT(condition)
akalin@chromium.orgf6b59fa2010-10-01 11:58:24 +0900549#define DPLOG_IF(severity, condition) PLOG_IF(severity, condition)
akalin@chromium.orga88579b2010-10-02 08:02:36 +0900550#define DVLOG_IF(verboselevel, condition) VLOG_IF(verboselevel, condition)
akalin@chromium.orgf6b59fa2010-10-01 11:58:24 +0900551
552#else // ENABLE_DLOG
553
akalin@chromium.orga88579b2010-10-02 08:02:36 +0900554// If ENABLE_DLOG is off, we want to avoid emitting any references to
555// |condition| (which may reference a variable defined only if NDEBUG
556// is not defined). Contrast this with DCHECK et al., which has
557// different behavior.
akalin@chromium.orgf6b59fa2010-10-01 11:58:24 +0900558
akalin@chromium.orga88579b2010-10-02 08:02:36 +0900559#define DLOG_EAT_STREAM_PARAMETERS \
560 true ? (void) 0 : ::logging::LogMessageVoidify() & LOG_STREAM(FATAL)
akalin@chromium.orgf6b59fa2010-10-01 11:58:24 +0900561
akalin@chromium.org25cef532010-11-02 04:49:22 +0900562#define DLOG_IS_ON(severity) false
akalin@chromium.orga88579b2010-10-02 08:02:36 +0900563#define DLOG_IF(severity, condition) DLOG_EAT_STREAM_PARAMETERS
564#define DLOG_ASSERT(condition) DLOG_EAT_STREAM_PARAMETERS
565#define DPLOG_IF(severity, condition) DLOG_EAT_STREAM_PARAMETERS
566#define DVLOG_IF(verboselevel, condition) DLOG_EAT_STREAM_PARAMETERS
akalin@chromium.orgf6b59fa2010-10-01 11:58:24 +0900567
568#endif // ENABLE_DLOG
569
akalin@chromium.org85510482010-10-01 06:12:33 +0900570// DEBUG_MODE is for uses like
571// if (DEBUG_MODE) foo.CheckThatFoo();
572// instead of
573// #ifndef NDEBUG
574// foo.CheckThatFoo();
575// #endif
576//
577// We tie its state to ENABLE_DLOG.
578enum { DEBUG_MODE = ENABLE_DLOG };
579
580#undef ENABLE_DLOG
581
akalin@chromium.orga88579b2010-10-02 08:02:36 +0900582#define DLOG(severity) \
583 LAZY_STREAM(LOG_STREAM(severity), DLOG_IS_ON(severity))
584
585#if defined(OS_WIN)
586#define DLOG_GETLASTERROR(severity) \
587 LAZY_STREAM(LOG_GETLASTERROR_STREAM(severity), DLOG_IS_ON(severity))
588#define DLOG_GETLASTERROR_MODULE(severity, module) \
589 LAZY_STREAM(LOG_GETLASTERROR_STREAM(severity, module), \
590 DLOG_IS_ON(severity))
591#elif defined(OS_POSIX)
592#define DLOG_ERRNO(severity) \
593 LAZY_STREAM(LOG_ERRNO_STREAM(severity), DLOG_IS_ON(severity))
594#endif
595
596#define DPLOG(severity) \
597 LAZY_STREAM(PLOG_STREAM(severity), DLOG_IS_ON(severity))
598
599#define DVLOG(verboselevel) DLOG_IF(INFO, VLOG_IS_ON(verboselevel))
600
601// Definitions for DCHECK et al.
akalin@chromium.orgf6b59fa2010-10-01 11:58:24 +0900602
akalin@chromium.org85510482010-10-01 06:12:33 +0900603#if ENABLE_DCHECK
mark@chromium.org667f6212009-08-20 10:20:29 +0900604
akalin@chromium.orga88579b2010-10-02 08:02:36 +0900605#if defined(NDEBUG)
akalin@chromium.orgf6b59fa2010-10-01 11:58:24 +0900606
akalin@chromium.org434c5b62010-11-03 14:30:14 +0900607#define COMPACT_GOOGLE_LOG_EX_DCHECK(ClassName, ...) \
608 COMPACT_GOOGLE_LOG_EX_ERROR_REPORT(ClassName , ##__VA_ARGS__)
609#define COMPACT_GOOGLE_LOG_DCHECK COMPACT_GOOGLE_LOG_ERROR_REPORT
akalin@chromium.orga88579b2010-10-02 08:02:36 +0900610const LogSeverity LOG_DCHECK = LOG_ERROR_REPORT;
akalin@chromium.orgfaed5f82011-01-11 10:03:36 +0900611extern DcheckState g_dcheck_state;
612#define DCHECK_IS_ON() \
613 ((::logging::g_dcheck_state == \
614 ::logging::ENABLE_DCHECK_FOR_NON_OFFICIAL_RELEASE_BUILDS) && \
615 LOG_IS_ON(DCHECK))
akalin@chromium.orgf6b59fa2010-10-01 11:58:24 +0900616
akalin@chromium.orga88579b2010-10-02 08:02:36 +0900617#else // defined(NDEBUG)
618
akalin@chromium.org25cef532010-11-02 04:49:22 +0900619// On a regular debug build, we want to have DCHECKs enabled.
akalin@chromium.org434c5b62010-11-03 14:30:14 +0900620#define COMPACT_GOOGLE_LOG_EX_DCHECK(ClassName, ...) \
621 COMPACT_GOOGLE_LOG_EX_FATAL(ClassName , ##__VA_ARGS__)
622#define COMPACT_GOOGLE_LOG_DCHECK COMPACT_GOOGLE_LOG_FATAL
akalin@chromium.orga88579b2010-10-02 08:02:36 +0900623const LogSeverity LOG_DCHECK = LOG_FATAL;
akalin@chromium.org434c5b62010-11-03 14:30:14 +0900624#define DCHECK_IS_ON() true
akalin@chromium.orga88579b2010-10-02 08:02:36 +0900625
626#endif // defined(NDEBUG)
627
628#else // ENABLE_DCHECK
629
akalin@chromium.org434c5b62010-11-03 14:30:14 +0900630// These are just dummy values since DCHECK_IS_ON() is always false in
631// this case.
632#define COMPACT_GOOGLE_LOG_EX_DCHECK(ClassName, ...) \
633 COMPACT_GOOGLE_LOG_EX_INFO(ClassName , ##__VA_ARGS__)
634#define COMPACT_GOOGLE_LOG_DCHECK COMPACT_GOOGLE_LOG_INFO
635const LogSeverity LOG_DCHECK = LOG_INFO;
akalin@chromium.org25cef532010-11-02 04:49:22 +0900636#define DCHECK_IS_ON() false
akalin@chromium.orga88579b2010-10-02 08:02:36 +0900637
638#endif // ENABLE_DCHECK
akalin@chromium.org25cef532010-11-02 04:49:22 +0900639#undef ENABLE_DCHECK
akalin@chromium.orga88579b2010-10-02 08:02:36 +0900640
akalin@chromium.org434c5b62010-11-03 14:30:14 +0900641// DCHECK et al. make sure to reference |condition| regardless of
akalin@chromium.orga88579b2010-10-02 08:02:36 +0900642// whether DCHECKs are enabled; this is so that we don't get unused
643// variable warnings if the only use of a variable is in a DCHECK.
644// This behavior is different from DLOG_IF et al.
645
akalin@chromium.org434c5b62010-11-03 14:30:14 +0900646#define DCHECK(condition) \
647 LAZY_STREAM(LOG_STREAM(DCHECK), DCHECK_IS_ON() && !(condition)) \
akalin@chromium.orga88579b2010-10-02 08:02:36 +0900648 << "Check failed: " #condition ". "
649
akalin@chromium.org434c5b62010-11-03 14:30:14 +0900650#define DPCHECK(condition) \
651 LAZY_STREAM(PLOG_STREAM(DCHECK), DCHECK_IS_ON() && !(condition)) \
akalin@chromium.orga88579b2010-10-02 08:02:36 +0900652 << "Check failed: " #condition ". "
akalin@chromium.orgf6b59fa2010-10-01 11:58:24 +0900653
654// Helper macro for binary operators.
655// Don't use this macro directly in your code, use DCHECK_EQ et al below.
akalin@chromium.orga88579b2010-10-02 08:02:36 +0900656#define DCHECK_OP(name, op, val1, val2) \
akalin@chromium.org25cef532010-11-02 04:49:22 +0900657 if (DCHECK_IS_ON()) \
akalin@chromium.orga88579b2010-10-02 08:02:36 +0900658 if (logging::CheckOpString _result = \
659 logging::Check##name##Impl((val1), (val2), \
660 #val1 " " #op " " #val2)) \
661 logging::LogMessage( \
662 __FILE__, __LINE__, ::logging::LOG_DCHECK, \
663 _result).stream()
initial.commit3f4a7322008-07-27 06:49:38 +0900664
akalin@chromium.org434c5b62010-11-03 14:30:14 +0900665// Equality/Inequality checks - compare two values, and log a
666// LOG_DCHECK message including the two values when the result is not
667// as expected. The values must have operator<<(ostream, ...)
668// defined.
initial.commit3f4a7322008-07-27 06:49:38 +0900669//
670// You may append to the error message like so:
671// DCHECK_NE(1, 2) << ": The world must be ending!";
672//
673// We are very careful to ensure that each argument is evaluated exactly
674// once, and that anything which is legal to pass as a function argument is
675// legal here. In particular, the arguments may be temporary expressions
676// which will end up being destroyed at the end of the apparent statement,
677// for example:
678// DCHECK_EQ(string("abc")[1], 'b');
679//
680// WARNING: These may not compile correctly if one of the arguments is a pointer
681// and the other is NULL. To work around this, simply static_cast NULL to the
682// type of the desired pointer.
683
684#define DCHECK_EQ(val1, val2) DCHECK_OP(EQ, ==, val1, val2)
685#define DCHECK_NE(val1, val2) DCHECK_OP(NE, !=, val1, val2)
686#define DCHECK_LE(val1, val2) DCHECK_OP(LE, <=, val1, val2)
687#define DCHECK_LT(val1, val2) DCHECK_OP(LT, < , val1, val2)
688#define DCHECK_GE(val1, val2) DCHECK_OP(GE, >=, val1, val2)
689#define DCHECK_GT(val1, val2) DCHECK_OP(GT, > , val1, val2)
690
initial.commit3f4a7322008-07-27 06:49:38 +0900691#define NOTREACHED() DCHECK(false)
692
693// Redefine the standard assert to use our nice log files
694#undef assert
695#define assert(x) DLOG_ASSERT(x)
696
697// This class more or less represents a particular log message. You
698// create an instance of LogMessage and then stream stuff to it.
699// When you finish streaming to it, ~LogMessage is called and the
700// full message gets streamed to the appropriate destination.
701//
702// You shouldn't actually use LogMessage's constructor to log things,
703// though. You should use the LOG() macro (and variants thereof)
704// above.
705class LogMessage {
706 public:
707 LogMessage(const char* file, int line, LogSeverity severity, int ctr);
708
709 // Two special constructors that generate reduced amounts of code at
710 // LOG call sites for common cases.
711 //
712 // Used for LOG(INFO): Implied are:
713 // severity = LOG_INFO, ctr = 0
714 //
715 // Using this constructor instead of the more complex constructor above
716 // saves a couple of bytes per call site.
717 LogMessage(const char* file, int line);
718
719 // Used for LOG(severity) where severity != INFO. Implied
720 // are: ctr = 0
721 //
722 // Using this constructor instead of the more complex constructor above
723 // saves a couple of bytes per call site.
724 LogMessage(const char* file, int line, LogSeverity severity);
725
726 // A special constructor used for check failures.
727 // Implied severity = LOG_FATAL
728 LogMessage(const char* file, int line, const CheckOpString& result);
729
huanr@chromium.org656253e2009-02-12 10:19:05 +0900730 // A special constructor used for check failures, with the option to
731 // specify severity.
732 LogMessage(const char* file, int line, LogSeverity severity,
733 const CheckOpString& result);
734
initial.commit3f4a7322008-07-27 06:49:38 +0900735 ~LogMessage();
736
737 std::ostream& stream() { return stream_; }
738
739 private:
740 void Init(const char* file, int line);
741
742 LogSeverity severity_;
743 std::ostringstream stream_;
maruel@google.coma855b0f2008-07-30 22:02:03 +0900744 size_t message_start_; // Offset of the start of the message (past prefix
745 // info).
siggi@chromium.org25396e12010-11-05 00:50:49 +0900746 // The file and line information passed in to the constructor.
747 const char* file_;
748 const int line_;
749
tommi@google.com82788e12009-04-15 01:52:11 +0900750#if defined(OS_WIN)
751 // Stores the current value of GetLastError in the constructor and restores
752 // it in the destructor by calling SetLastError.
753 // This is useful since the LogMessage class uses a lot of Win32 calls
754 // that will lose the value of GLE and the code that called the log function
755 // will have lost the thread error value when the log call returns.
756 class SaveLastError {
757 public:
758 SaveLastError();
759 ~SaveLastError();
760
761 unsigned long get_error() const { return last_error_; }
762
763 protected:
764 unsigned long last_error_;
765 };
766
767 SaveLastError last_error_;
768#endif
initial.commit3f4a7322008-07-27 06:49:38 +0900769
brettw@google.come3c034a2008-08-08 03:31:40 +0900770 DISALLOW_COPY_AND_ASSIGN(LogMessage);
initial.commit3f4a7322008-07-27 06:49:38 +0900771};
772
773// A non-macro interface to the log facility; (useful
774// when the logging level is not a compile-time constant).
775inline void LogAtLevel(int const log_level, std::string const &msg) {
776 LogMessage(__FILE__, __LINE__, log_level).stream() << msg;
777}
778
779// This class is used to explicitly ignore values in the conditional
780// logging macros. This avoids compiler warnings like "value computed
781// is not used" and "statement has no effect".
782class LogMessageVoidify {
783 public:
784 LogMessageVoidify() { }
785 // This has to be an operator with a precedence lower than << but
786 // higher than ?:
787 void operator&(std::ostream&) { }
788};
789
tschmelcher@chromium.orgf29a4fc2009-10-10 08:52:20 +0900790#if defined(OS_WIN)
791typedef unsigned long SystemErrorCode;
792#elif defined(OS_POSIX)
793typedef int SystemErrorCode;
794#endif
795
796// Alias for ::GetLastError() on Windows and errno on POSIX. Avoids having to
797// pull in windows.h just for GetLastError() and DWORD.
798SystemErrorCode GetLastSystemErrorCode();
799
800#if defined(OS_WIN)
801// Appends a formatted system message of the GetLastError() type.
802class Win32ErrorLogMessage {
803 public:
804 Win32ErrorLogMessage(const char* file,
805 int line,
806 LogSeverity severity,
807 SystemErrorCode err,
808 const char* module);
809
810 Win32ErrorLogMessage(const char* file,
811 int line,
812 LogSeverity severity,
813 SystemErrorCode err);
814
tschmelcher@chromium.orgf29a4fc2009-10-10 08:52:20 +0900815 // Appends the error message before destructing the encapsulated class.
816 ~Win32ErrorLogMessage();
817
erg@google.comd5fffd42011-01-08 03:06:45 +0900818 std::ostream& stream() { return log_message_.stream(); }
819
tschmelcher@chromium.orgf29a4fc2009-10-10 08:52:20 +0900820 private:
821 SystemErrorCode err_;
822 // Optional name of the module defining the error.
823 const char* module_;
824 LogMessage log_message_;
825
826 DISALLOW_COPY_AND_ASSIGN(Win32ErrorLogMessage);
827};
828#elif defined(OS_POSIX)
829// Appends a formatted system message of the errno type
830class ErrnoLogMessage {
831 public:
832 ErrnoLogMessage(const char* file,
833 int line,
834 LogSeverity severity,
835 SystemErrorCode err);
836
tschmelcher@chromium.orgf29a4fc2009-10-10 08:52:20 +0900837 // Appends the error message before destructing the encapsulated class.
838 ~ErrnoLogMessage();
839
erg@google.comd5fffd42011-01-08 03:06:45 +0900840 std::ostream& stream() { return log_message_.stream(); }
841
tschmelcher@chromium.orgf29a4fc2009-10-10 08:52:20 +0900842 private:
843 SystemErrorCode err_;
844 LogMessage log_message_;
845
846 DISALLOW_COPY_AND_ASSIGN(ErrnoLogMessage);
847};
848#endif // OS_WIN
849
initial.commit3f4a7322008-07-27 06:49:38 +0900850// Closes the log file explicitly if open.
851// NOTE: Since the log file is opened as necessary by the action of logging
852// statements, there's no guarantee that it will stay closed
853// after this call.
854void CloseLogFile();
855
willchan@chromium.org85113a12009-12-08 13:22:50 +0900856// Async signal safe logging mechanism.
857void RawLog(int level, const char* message);
858
859#define RAW_LOG(level, message) logging::RawLog(logging::LOG_ ## level, message)
860
861#define RAW_CHECK(condition) \
862 do { \
863 if (!(condition)) \
864 logging::RawLog(logging::LOG_FATAL, "Check failed: " #condition "\n"); \
865 } while (0)
866
brettw@google.come3c034a2008-08-08 03:31:40 +0900867} // namespace logging
initial.commit3f4a7322008-07-27 06:49:38 +0900868
thakis@chromium.orgb13bd1d2010-06-17 03:39:53 +0900869// These functions are provided as a convenience for logging, which is where we
870// use streams (it is against Google style to use streams in other places). It
871// is designed to allow you to emit non-ASCII Unicode strings to the log file,
872// which is normally ASCII. It is relatively slow, so try not to use it for
873// common cases. Non-ASCII characters will be converted to UTF-8 by these
874// operators.
875std::ostream& operator<<(std::ostream& out, const wchar_t* wstr);
876inline std::ostream& operator<<(std::ostream& out, const std::wstring& wstr) {
877 return out << wstr.c_str();
878}
879
ericroman@google.comfa95b462008-08-25 12:44:40 +0900880// The NOTIMPLEMENTED() macro annotates codepaths which have
881// not been implemented yet.
882//
883// The implementation of this macro is controlled by NOTIMPLEMENTED_POLICY:
884// 0 -- Do nothing (stripped by compiler)
885// 1 -- Warn at compile time
886// 2 -- Fail at compile time
887// 3 -- Fail at runtime (DCHECK)
888// 4 -- [default] LOG(ERROR) at runtime
889// 5 -- LOG(ERROR) at runtime, only once per call-site
890
891#ifndef NOTIMPLEMENTED_POLICY
892// Select default policy: LOG(ERROR)
893#define NOTIMPLEMENTED_POLICY 4
894#endif
895
agl@chromium.orgfc910612008-10-31 08:54:26 +0900896#if defined(COMPILER_GCC)
897// On Linux, with GCC, we can use __PRETTY_FUNCTION__ to get the demangled name
898// of the current function in the NOTIMPLEMENTED message.
899#define NOTIMPLEMENTED_MSG "Not implemented reached in " << __PRETTY_FUNCTION__
900#else
901#define NOTIMPLEMENTED_MSG "NOT IMPLEMENTED"
902#endif
903
ericroman@google.comfa95b462008-08-25 12:44:40 +0900904#if NOTIMPLEMENTED_POLICY == 0
905#define NOTIMPLEMENTED() ;
906#elif NOTIMPLEMENTED_POLICY == 1
907// TODO, figure out how to generate a warning
908#define NOTIMPLEMENTED() COMPILE_ASSERT(false, NOT_IMPLEMENTED)
909#elif NOTIMPLEMENTED_POLICY == 2
910#define NOTIMPLEMENTED() COMPILE_ASSERT(false, NOT_IMPLEMENTED)
911#elif NOTIMPLEMENTED_POLICY == 3
912#define NOTIMPLEMENTED() NOTREACHED()
913#elif NOTIMPLEMENTED_POLICY == 4
agl@chromium.orgfc910612008-10-31 08:54:26 +0900914#define NOTIMPLEMENTED() LOG(ERROR) << NOTIMPLEMENTED_MSG
ericroman@google.comfa95b462008-08-25 12:44:40 +0900915#elif NOTIMPLEMENTED_POLICY == 5
916#define NOTIMPLEMENTED() do {\
917 static int count = 0;\
agl@chromium.orgfc910612008-10-31 08:54:26 +0900918 LOG_IF(ERROR, 0 == count++) << NOTIMPLEMENTED_MSG;\
ericroman@google.comfa95b462008-08-25 12:44:40 +0900919} while(0)
920#endif
921
brettw@google.come3c034a2008-08-08 03:31:40 +0900922#endif // BASE_LOGGING_H_