blob: 6f30bcbe4f736f989bad178ac3d96ed70bf08943 [file] [log] [blame]
[email protected]34a907732012-01-20 06:33:271// Copyright (c) 2012 The Chromium Authors. All rights reserved.
license.botbf09a502008-08-24 00:55:552// 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
avi9b6f42932015-12-26 22:15:148#include <stddef.h>
9
[email protected]e7972d12011-06-18 11:53:1410#include <cassert>
initial.commitd7cae122008-07-26 21:49:3811#include <cstring>
12#include <sstream>
avi9b6f42932015-12-26 22:15:1413#include <string>
jbroman6bcfec422016-05-26 00:28:4614#include <type_traits>
15#include <utility>
initial.commitd7cae122008-07-26 21:49:3816
[email protected]0bea7252011-08-05 15:34:0017#include "base/base_export.h"
danakjcb7c5292016-12-20 19:05:3518#include "base/compiler_specific.h"
[email protected]ddb9b332011-12-02 07:31:0919#include "base/debug/debugger.h"
avi9b6f42932015-12-26 22:15:1420#include "base/macros.h"
jbroman6bcfec422016-05-26 00:28:4621#include "base/template_util.h"
[email protected]90509cb2011-03-25 18:46:3822#include "build/build_config.h"
initial.commitd7cae122008-07-26 21:49:3823
24//
25// Optional message capabilities
26// -----------------------------
27// Assertion failed messages and fatal errors are displayed in a dialog box
28// before the application exits. However, running this UI creates a message
29// loop, which causes application messages to be processed and potentially
30// dispatched to existing application windows. Since the application is in a
31// bad state when this assertion dialog is displayed, these messages may not
32// get processed and hang the dialog, or the application might go crazy.
33//
34// Therefore, it can be beneficial to display the error dialog in a separate
35// process from the main application. When the logging system needs to display
36// a fatal error dialog box, it will look for a program called
37// "DebugMessage.exe" in the same directory as the application executable. It
38// will run this application with the message as the command line, and will
39// not include the name of the application as is traditional for easier
40// parsing.
41//
42// The code for DebugMessage.exe is only one line. In WinMain, do:
43// MessageBox(NULL, GetCommandLineW(), L"Fatal Error", 0);
44//
45// If DebugMessage.exe is not found, the logging code will use a normal
46// MessageBox, potentially causing the problems discussed above.
47
48
49// Instructions
50// ------------
51//
52// Make a bunch of macros for logging. The way to log things is to stream
53// things to LOG(<a particular severity level>). E.g.,
54//
55// LOG(INFO) << "Found " << num_cookies << " cookies";
56//
57// You can also do conditional logging:
58//
59// LOG_IF(INFO, num_cookies > 10) << "Got lots of cookies";
60//
initial.commitd7cae122008-07-26 21:49:3861// The CHECK(condition) macro is active in both debug and release builds and
62// effectively performs a LOG(FATAL) which terminates the process and
63// generates a crashdump unless a debugger is attached.
64//
65// There are also "debug mode" logging macros like the ones above:
66//
67// DLOG(INFO) << "Found cookies";
68//
69// DLOG_IF(INFO, num_cookies > 10) << "Got lots of cookies";
70//
71// All "debug mode" logging is compiled away to nothing for non-debug mode
72// compiles. LOG_IF and development flags also work well together
73// because the code can be compiled away sometimes.
74//
75// We also have
76//
77// LOG_ASSERT(assertion);
78// DLOG_ASSERT(assertion);
79//
80// which is syntactic sugar for {,D}LOG_IF(FATAL, assert fails) << assertion;
81//
[email protected]99b7c57f2010-09-29 19:26:3682// There are "verbose level" logging macros. They look like
83//
84// VLOG(1) << "I'm printed when you run the program with --v=1 or more";
85// VLOG(2) << "I'm printed when you run the program with --v=2 or more";
86//
87// These always log at the INFO log level (when they log at all).
88// The verbose logging can also be turned on module-by-module. For instance,
[email protected]b0d38d4c2010-10-29 00:39:4889// --vmodule=profile=2,icon_loader=1,browser_*=3,*/chromeos/*=4 --v=0
[email protected]99b7c57f2010-09-29 19:26:3690// will cause:
91// a. VLOG(2) and lower messages to be printed from profile.{h,cc}
92// b. VLOG(1) and lower messages to be printed from icon_loader.{h,cc}
93// c. VLOG(3) and lower messages to be printed from files prefixed with
94// "browser"
[email protected]e11de722010-11-01 20:50:5595// d. VLOG(4) and lower messages to be printed from files under a
[email protected]b0d38d4c2010-10-29 00:39:4896// "chromeos" directory.
[email protected]e11de722010-11-01 20:50:5597// e. VLOG(0) and lower messages to be printed from elsewhere
[email protected]99b7c57f2010-09-29 19:26:3698//
99// The wildcarding functionality shown by (c) supports both '*' (match
[email protected]b0d38d4c2010-10-29 00:39:48100// 0 or more characters) and '?' (match any single character)
101// wildcards. Any pattern containing a forward or backward slash will
102// be tested against the whole pathname and not just the module.
103// E.g., "*/foo/bar/*=2" would change the logging level for all code
104// in source files under a "foo/bar" directory.
[email protected]99b7c57f2010-09-29 19:26:36105//
106// There's also VLOG_IS_ON(n) "verbose level" condition macro. To be used as
107//
108// if (VLOG_IS_ON(2)) {
109// // do some logging preparation and logging
110// // that can't be accomplished with just VLOG(2) << ...;
111// }
112//
113// There is also a VLOG_IF "verbose level" condition macro for sample
114// cases, when some extra computation and preparation for logs is not
115// needed.
116//
117// VLOG_IF(1, (size > 1024))
118// << "I'm printed when size is more than 1024 and when you run the "
119// "program with --v=1 or more";
120//
initial.commitd7cae122008-07-26 21:49:38121// We also override the standard 'assert' to use 'DLOG_ASSERT'.
122//
[email protected]d8617a62009-10-09 23:52:20123// Lastly, there is:
124//
125// PLOG(ERROR) << "Couldn't do foo";
126// DPLOG(ERROR) << "Couldn't do foo";
127// PLOG_IF(ERROR, cond) << "Couldn't do foo";
128// DPLOG_IF(ERROR, cond) << "Couldn't do foo";
129// PCHECK(condition) << "Couldn't do foo";
130// DPCHECK(condition) << "Couldn't do foo";
131//
132// which append the last system error to the message in string form (taken from
133// GetLastError() on Windows and errno on POSIX).
134//
initial.commitd7cae122008-07-26 21:49:38135// The supported severity levels for macros that allow you to specify one
[email protected]f2c05492014-06-17 12:04:23136// are (in increasing order of severity) INFO, WARNING, ERROR, and FATAL.
initial.commitd7cae122008-07-26 21:49:38137//
138// Very important: logging a message at the FATAL severity level causes
139// the program to terminate (after the message is logged).
[email protected]fb62a532009-02-12 01:19:05140//
[email protected]f2c05492014-06-17 12:04:23141// There is the special severity of DFATAL, which logs FATAL in debug mode,
142// ERROR in normal mode.
initial.commitd7cae122008-07-26 21:49:38143
144namespace logging {
145
[email protected]5e3f7c22013-06-21 21:15:33146// TODO(avi): do we want to do a unification of character types here?
147#if defined(OS_WIN)
148typedef wchar_t PathChar;
149#else
150typedef char PathChar;
151#endif
152
153// Where to record logging output? A flat file and/or system debug log
154// via OutputDebugString.
155enum LoggingDestination {
156 LOG_NONE = 0,
157 LOG_TO_FILE = 1 << 0,
158 LOG_TO_SYSTEM_DEBUG_LOG = 1 << 1,
159
160 LOG_TO_ALL = LOG_TO_FILE | LOG_TO_SYSTEM_DEBUG_LOG,
161
162 // On Windows, use a file next to the exe; on POSIX platforms, where
163 // it may not even be possible to locate the executable on disk, use
164 // stderr.
165#if defined(OS_WIN)
166 LOG_DEFAULT = LOG_TO_FILE,
167#elif defined(OS_POSIX)
168 LOG_DEFAULT = LOG_TO_SYSTEM_DEBUG_LOG,
169#endif
170};
initial.commitd7cae122008-07-26 21:49:38171
172// Indicates that the log file should be locked when being written to.
[email protected]5e3f7c22013-06-21 21:15:33173// Unless there is only one single-threaded process that is logging to
174// the log file, the file should be locked during writes to make each
[email protected]3ee50d12014-03-05 01:43:27175// log output atomic. Other writers will block.
initial.commitd7cae122008-07-26 21:49:38176//
177// All processes writing to the log file must have their locking set for it to
[email protected]5e3f7c22013-06-21 21:15:33178// work properly. Defaults to LOCK_LOG_FILE.
initial.commitd7cae122008-07-26 21:49:38179enum LogLockingState { LOCK_LOG_FILE, DONT_LOCK_LOG_FILE };
180
181// On startup, should we delete or append to an existing log file (if any)?
182// Defaults to APPEND_TO_OLD_LOG_FILE.
183enum OldFileDeletionState { DELETE_OLD_LOG_FILE, APPEND_TO_OLD_LOG_FILE };
184
[email protected]5e3f7c22013-06-21 21:15:33185struct BASE_EXPORT LoggingSettings {
186 // The defaults values are:
187 //
188 // logging_dest: LOG_DEFAULT
189 // log_file: NULL
190 // lock_log: LOCK_LOG_FILE
191 // delete_old: APPEND_TO_OLD_LOG_FILE
[email protected]5e3f7c22013-06-21 21:15:33192 LoggingSettings();
193
194 LoggingDestination logging_dest;
195
196 // The three settings below have an effect only when LOG_TO_FILE is
197 // set in |logging_dest|.
198 const PathChar* log_file;
199 LogLockingState lock_log;
200 OldFileDeletionState delete_old;
[email protected]5e3f7c22013-06-21 21:15:33201};
[email protected]ff3d0c32010-08-23 19:57:46202
203// Define different names for the BaseInitLoggingImpl() function depending on
204// whether NDEBUG is defined or not so that we'll fail to link if someone tries
205// to compile logging.cc with NDEBUG but includes logging.h without defining it,
206// or vice versa.
207#if NDEBUG
208#define BaseInitLoggingImpl BaseInitLoggingImpl_built_with_NDEBUG
209#else
210#define BaseInitLoggingImpl BaseInitLoggingImpl_built_without_NDEBUG
211#endif
212
213// Implementation of the InitLogging() method declared below. We use a
214// more-specific name so we can #define it above without affecting other code
215// that has named stuff "InitLogging".
[email protected]5e3f7c22013-06-21 21:15:33216BASE_EXPORT bool BaseInitLoggingImpl(const LoggingSettings& settings);
[email protected]ff3d0c32010-08-23 19:57:46217
initial.commitd7cae122008-07-26 21:49:38218// Sets the log file name and other global logging state. Calling this function
219// is recommended, and is normally done at the beginning of application init.
220// If you don't call it, all the flags will be initialized to their default
221// values, and there is a race condition that may leak a critical section
222// object if two threads try to do the first log at the same time.
223// See the definition of the enums above for descriptions and default values.
224//
225// The default log file is initialized to "debug.log" in the application
226// directory. You probably don't want this, especially since the program
227// directory may not be writable on an enduser's system.
[email protected]064aa162011-12-03 00:30:08228//
229// This function may be called a second time to re-direct logging (e.g after
230// loging in to a user partition), however it should never be called more than
231// twice.
[email protected]5e3f7c22013-06-21 21:15:33232inline bool InitLogging(const LoggingSettings& settings) {
233 return BaseInitLoggingImpl(settings);
[email protected]ff3d0c32010-08-23 19:57:46234}
initial.commitd7cae122008-07-26 21:49:38235
236// Sets the log level. Anything at or above this level will be written to the
237// log file/displayed to the user (if applicable). Anything below this level
[email protected]162ac0f2010-11-04 15:50:49238// will be silently ignored. The log level defaults to 0 (everything is logged
239// up to level INFO) if this function is not called.
240// Note that log messages for VLOG(x) are logged at level -x, so setting
241// the min log level to negative values enables verbose logging.
[email protected]0bea7252011-08-05 15:34:00242BASE_EXPORT void SetMinLogLevel(int level);
initial.commitd7cae122008-07-26 21:49:38243
[email protected]8a2986ca2009-04-10 19:13:42244// Gets the current log level.
[email protected]0bea7252011-08-05 15:34:00245BASE_EXPORT int GetMinLogLevel();
initial.commitd7cae122008-07-26 21:49:38246
skobesc78c0ad72015-12-07 20:21:23247// Used by LOG_IS_ON to lazy-evaluate stream arguments.
248BASE_EXPORT bool ShouldCreateLogMessage(int severity);
249
[email protected]162ac0f2010-11-04 15:50:49250// Gets the VLOG default verbosity level.
[email protected]0bea7252011-08-05 15:34:00251BASE_EXPORT int GetVlogVerbosity();
[email protected]162ac0f2010-11-04 15:50:49252
[email protected]99b7c57f2010-09-29 19:26:36253// Gets the current vlog level for the given file (usually taken from
254// __FILE__).
[email protected]2f4e9a62010-09-29 21:25:14255
256// Note that |N| is the size *with* the null terminator.
[email protected]0bea7252011-08-05 15:34:00257BASE_EXPORT int GetVlogLevelHelper(const char* file_start, size_t N);
[email protected]2f4e9a62010-09-29 21:25:14258
[email protected]99b7c57f2010-09-29 19:26:36259template <size_t N>
260int GetVlogLevel(const char (&file)[N]) {
261 return GetVlogLevelHelper(file, N);
262}
initial.commitd7cae122008-07-26 21:49:38263
264// Sets the common items you want to be prepended to each log message.
265// process and thread IDs default to off, the timestamp defaults to on.
266// If this function is not called, logging defaults to writing the timestamp
267// only.
[email protected]0bea7252011-08-05 15:34:00268BASE_EXPORT void SetLogItems(bool enable_process_id, bool enable_thread_id,
269 bool enable_timestamp, bool enable_tickcount);
initial.commitd7cae122008-07-26 21:49:38270
[email protected]81e0a852010-08-17 00:38:12271// Sets whether or not you'd like to see fatal debug messages popped up in
272// a dialog box or not.
273// Dialogs are not shown by default.
[email protected]0bea7252011-08-05 15:34:00274BASE_EXPORT void SetShowErrorDialogs(bool enable_dialogs);
[email protected]81e0a852010-08-17 00:38:12275
initial.commitd7cae122008-07-26 21:49:38276// Sets the Log Assert Handler that will be used to notify of check failures.
[email protected]fb62a532009-02-12 01:19:05277// The default handler shows a dialog box and then terminate the process,
278// however clients can use this function to override with their own handling
279// (e.g. a silent one for Unit Tests)
initial.commitd7cae122008-07-26 21:49:38280typedef void (*LogAssertHandlerFunction)(const std::string& str);
[email protected]0bea7252011-08-05 15:34:00281BASE_EXPORT void SetLogAssertHandler(LogAssertHandlerFunction handler);
[email protected]64e5cc02010-11-03 19:20:27282
[email protected]2b07b8412009-11-25 15:26:34283// Sets the Log Message Handler that gets passed every log message before
284// it's sent to other log destinations (if any).
285// Returns true to signal that it handled the message and the message
286// should not be sent to other log destinations.
[email protected]162ac0f2010-11-04 15:50:49287typedef bool (*LogMessageHandlerFunction)(int severity,
288 const char* file, int line, size_t message_start, const std::string& str);
[email protected]0bea7252011-08-05 15:34:00289BASE_EXPORT void SetLogMessageHandler(LogMessageHandlerFunction handler);
290BASE_EXPORT LogMessageHandlerFunction GetLogMessageHandler();
[email protected]2b07b8412009-11-25 15:26:34291
kmarshalle23eed02017-02-11 02:13:23292// ANALYZER_ASSUME_TRUE(...) generates compiler-specific annotations which
293// prevent the static analyzer from analyzing the code using hypothetical
294// values that are asserted to be impossible.
295// The value of the condition passed to ANALYZER_ASSUME_TRUE() is returned
296// directly.
297#if defined(__clang_analyzer__)
298
299inline void AnalyzerNoReturn() __attribute__((analyzer_noreturn)) {}
300
301template <typename TVal>
302inline constexpr TVal AnalysisAssumeTrue(TVal arg) {
303 if (!arg) {
304 AnalyzerNoReturn();
305 }
306 return arg;
307}
308
309#define ANALYZER_ASSUME_TRUE(val) ::logging::AnalysisAssumeTrue(val)
310
311#elif defined(_PREFAST_) && defined(OS_WIN)
312
313template <typename TVal>
314inline constexpr TVal AnalysisAssumeTrue(TVal arg) {
315 __analysis_assume(!!arg);
316 return arg;
317}
318
319#define ANALYZER_ASSUME_TRUE(val) ::logging::AnalysisAssumeTrue(val)
320
321#else // !_PREFAST_ & !__clang_analyzer__
322
323#define ANALYZER_ASSUME_TRUE(val) (val)
324
325#endif // !_PREFAST_ & !__clang_analyzer__
326
initial.commitd7cae122008-07-26 21:49:38327typedef int LogSeverity;
[email protected]162ac0f2010-11-04 15:50:49328const LogSeverity LOG_VERBOSE = -1; // This is level 1 verbosity
329// Note: the log severities are used to index into the array of names,
330// see log_severity_names.
initial.commitd7cae122008-07-26 21:49:38331const LogSeverity LOG_INFO = 0;
332const LogSeverity LOG_WARNING = 1;
333const LogSeverity LOG_ERROR = 2;
[email protected]f2c05492014-06-17 12:04:23334const LogSeverity LOG_FATAL = 3;
335const LogSeverity LOG_NUM_SEVERITIES = 4;
initial.commitd7cae122008-07-26 21:49:38336
[email protected]521b0c42010-10-01 23:02:36337// LOG_DFATAL is LOG_FATAL in debug mode, ERROR in normal mode
initial.commitd7cae122008-07-26 21:49:38338#ifdef NDEBUG
[email protected]521b0c42010-10-01 23:02:36339const LogSeverity LOG_DFATAL = LOG_ERROR;
initial.commitd7cae122008-07-26 21:49:38340#else
[email protected]521b0c42010-10-01 23:02:36341const LogSeverity LOG_DFATAL = LOG_FATAL;
initial.commitd7cae122008-07-26 21:49:38342#endif
343
344// A few definitions of macros that don't generate much code. These are used
345// by LOG() and LOG_IF, etc. Since these are used all over our code, it's
346// better to have compact code for these operations.
[email protected]d8617a62009-10-09 23:52:20347#define COMPACT_GOOGLE_LOG_EX_INFO(ClassName, ...) \
tsniatowski612550f2016-07-21 18:26:20348 ::logging::ClassName(__FILE__, __LINE__, ::logging::LOG_INFO, ##__VA_ARGS__)
349#define COMPACT_GOOGLE_LOG_EX_WARNING(ClassName, ...) \
350 ::logging::ClassName(__FILE__, __LINE__, ::logging::LOG_WARNING, \
351 ##__VA_ARGS__)
[email protected]d8617a62009-10-09 23:52:20352#define COMPACT_GOOGLE_LOG_EX_ERROR(ClassName, ...) \
tsniatowski612550f2016-07-21 18:26:20353 ::logging::ClassName(__FILE__, __LINE__, ::logging::LOG_ERROR, ##__VA_ARGS__)
[email protected]d8617a62009-10-09 23:52:20354#define COMPACT_GOOGLE_LOG_EX_FATAL(ClassName, ...) \
tsniatowski612550f2016-07-21 18:26:20355 ::logging::ClassName(__FILE__, __LINE__, ::logging::LOG_FATAL, ##__VA_ARGS__)
[email protected]d8617a62009-10-09 23:52:20356#define COMPACT_GOOGLE_LOG_EX_DFATAL(ClassName, ...) \
tsniatowski612550f2016-07-21 18:26:20357 ::logging::ClassName(__FILE__, __LINE__, ::logging::LOG_DFATAL, ##__VA_ARGS__)
[email protected]d8617a62009-10-09 23:52:20358
initial.commitd7cae122008-07-26 21:49:38359#define COMPACT_GOOGLE_LOG_INFO \
[email protected]d8617a62009-10-09 23:52:20360 COMPACT_GOOGLE_LOG_EX_INFO(LogMessage)
initial.commitd7cae122008-07-26 21:49:38361#define COMPACT_GOOGLE_LOG_WARNING \
[email protected]d8617a62009-10-09 23:52:20362 COMPACT_GOOGLE_LOG_EX_WARNING(LogMessage)
initial.commitd7cae122008-07-26 21:49:38363#define COMPACT_GOOGLE_LOG_ERROR \
[email protected]d8617a62009-10-09 23:52:20364 COMPACT_GOOGLE_LOG_EX_ERROR(LogMessage)
initial.commitd7cae122008-07-26 21:49:38365#define COMPACT_GOOGLE_LOG_FATAL \
[email protected]d8617a62009-10-09 23:52:20366 COMPACT_GOOGLE_LOG_EX_FATAL(LogMessage)
initial.commitd7cae122008-07-26 21:49:38367#define COMPACT_GOOGLE_LOG_DFATAL \
[email protected]d8617a62009-10-09 23:52:20368 COMPACT_GOOGLE_LOG_EX_DFATAL(LogMessage)
initial.commitd7cae122008-07-26 21:49:38369
[email protected]8d127302013-01-10 02:41:57370#if defined(OS_WIN)
initial.commitd7cae122008-07-26 21:49:38371// wingdi.h defines ERROR to be 0. When we call LOG(ERROR), it gets
372// substituted with 0, and it expands to COMPACT_GOOGLE_LOG_0. To allow us
373// to keep using this syntax, we define this macro to do the same thing
374// as COMPACT_GOOGLE_LOG_ERROR, and also define ERROR the same way that
375// the Windows SDK does for consistency.
376#define ERROR 0
[email protected]d8617a62009-10-09 23:52:20377#define COMPACT_GOOGLE_LOG_EX_0(ClassName, ...) \
378 COMPACT_GOOGLE_LOG_EX_ERROR(ClassName , ##__VA_ARGS__)
379#define COMPACT_GOOGLE_LOG_0 COMPACT_GOOGLE_LOG_ERROR
[email protected]521b0c42010-10-01 23:02:36380// Needed for LOG_IS_ON(ERROR).
381const LogSeverity LOG_0 = LOG_ERROR;
[email protected]8d127302013-01-10 02:41:57382#endif
[email protected]521b0c42010-10-01 23:02:36383
[email protected]f2c05492014-06-17 12:04:23384// As special cases, we can assume that LOG_IS_ON(FATAL) always holds. Also,
385// LOG_IS_ON(DFATAL) always holds in debug mode. In particular, CHECK()s will
386// always fire if they fail.
[email protected]521b0c42010-10-01 23:02:36387#define LOG_IS_ON(severity) \
skobesc78c0ad72015-12-07 20:21:23388 (::logging::ShouldCreateLogMessage(::logging::LOG_##severity))
[email protected]521b0c42010-10-01 23:02:36389
390// We can't do any caching tricks with VLOG_IS_ON() like the
391// google-glog version since it requires GCC extensions. This means
392// that using the v-logging functions in conjunction with --vmodule
393// may be slow.
394#define VLOG_IS_ON(verboselevel) \
395 ((verboselevel) <= ::logging::GetVlogLevel(__FILE__))
396
397// Helper macro which avoids evaluating the arguments to a stream if
chcunninghamf6a96082015-02-07 01:58:37398// the condition doesn't hold. Condition is evaluated once and only once.
[email protected]521b0c42010-10-01 23:02:36399#define LAZY_STREAM(stream, condition) \
400 !(condition) ? (void) 0 : ::logging::LogMessageVoidify() & (stream)
initial.commitd7cae122008-07-26 21:49:38401
402// We use the preprocessor's merging operator, "##", so that, e.g.,
403// LOG(INFO) becomes the token COMPACT_GOOGLE_LOG_INFO. There's some funny
404// subtle difference between ostream member streaming functions (e.g.,
405// ostream::operator<<(int) and ostream non-member streaming functions
406// (e.g., ::operator<<(ostream&, string&): it turns out that it's
407// impossible to stream something like a string directly to an unnamed
408// ostream. We employ a neat hack by calling the stream() member
409// function of LogMessage which seems to avoid the problem.
[email protected]521b0c42010-10-01 23:02:36410#define LOG_STREAM(severity) COMPACT_GOOGLE_LOG_ ## severity.stream()
initial.commitd7cae122008-07-26 21:49:38411
[email protected]521b0c42010-10-01 23:02:36412#define LOG(severity) LAZY_STREAM(LOG_STREAM(severity), LOG_IS_ON(severity))
413#define LOG_IF(severity, condition) \
414 LAZY_STREAM(LOG_STREAM(severity), LOG_IS_ON(severity) && (condition))
415
[email protected]162ac0f2010-11-04 15:50:49416// The VLOG macros log with negative verbosities.
417#define VLOG_STREAM(verbose_level) \
tsniatowski612550f2016-07-21 18:26:20418 ::logging::LogMessage(__FILE__, __LINE__, -verbose_level).stream()
[email protected]162ac0f2010-11-04 15:50:49419
420#define VLOG(verbose_level) \
421 LAZY_STREAM(VLOG_STREAM(verbose_level), VLOG_IS_ON(verbose_level))
422
423#define VLOG_IF(verbose_level, condition) \
424 LAZY_STREAM(VLOG_STREAM(verbose_level), \
425 VLOG_IS_ON(verbose_level) && (condition))
[email protected]99b7c57f2010-09-29 19:26:36426
[email protected]fb879b1a2011-03-06 18:16:31427#if defined (OS_WIN)
428#define VPLOG_STREAM(verbose_level) \
tsniatowski612550f2016-07-21 18:26:20429 ::logging::Win32ErrorLogMessage(__FILE__, __LINE__, -verbose_level, \
[email protected]fb879b1a2011-03-06 18:16:31430 ::logging::GetLastSystemErrorCode()).stream()
431#elif defined(OS_POSIX)
432#define VPLOG_STREAM(verbose_level) \
tsniatowski612550f2016-07-21 18:26:20433 ::logging::ErrnoLogMessage(__FILE__, __LINE__, -verbose_level, \
[email protected]fb879b1a2011-03-06 18:16:31434 ::logging::GetLastSystemErrorCode()).stream()
435#endif
436
437#define VPLOG(verbose_level) \
438 LAZY_STREAM(VPLOG_STREAM(verbose_level), VLOG_IS_ON(verbose_level))
439
440#define VPLOG_IF(verbose_level, condition) \
441 LAZY_STREAM(VPLOG_STREAM(verbose_level), \
442 VLOG_IS_ON(verbose_level) && (condition))
443
[email protected]99b7c57f2010-09-29 19:26:36444// TODO(akalin): Add more VLOG variants, e.g. VPLOG.
initial.commitd7cae122008-07-26 21:49:38445
kmarshalle23eed02017-02-11 02:13:23446#define LOG_ASSERT(condition) \
447 LOG_IF(FATAL, !ANALYZER_ASSUME_TRUE(condition)) \
448 << "Assert failed: " #condition ". "
initial.commitd7cae122008-07-26 21:49:38449
[email protected]d8617a62009-10-09 23:52:20450#if defined(OS_WIN)
[email protected]c914d8a2014-04-23 01:11:01451#define PLOG_STREAM(severity) \
[email protected]d8617a62009-10-09 23:52:20452 COMPACT_GOOGLE_LOG_EX_ ## severity(Win32ErrorLogMessage, \
453 ::logging::GetLastSystemErrorCode()).stream()
[email protected]d8617a62009-10-09 23:52:20454#elif defined(OS_POSIX)
[email protected]c914d8a2014-04-23 01:11:01455#define PLOG_STREAM(severity) \
[email protected]d8617a62009-10-09 23:52:20456 COMPACT_GOOGLE_LOG_EX_ ## severity(ErrnoLogMessage, \
457 ::logging::GetLastSystemErrorCode()).stream()
[email protected]d8617a62009-10-09 23:52:20458#endif
459
[email protected]521b0c42010-10-01 23:02:36460#define PLOG(severity) \
461 LAZY_STREAM(PLOG_STREAM(severity), LOG_IS_ON(severity))
462
[email protected]d8617a62009-10-09 23:52:20463#define PLOG_IF(severity, condition) \
[email protected]521b0c42010-10-01 23:02:36464 LAZY_STREAM(PLOG_STREAM(severity), LOG_IS_ON(severity) && (condition))
[email protected]d8617a62009-10-09 23:52:20465
scottmg3c957a52016-12-10 20:57:59466BASE_EXPORT extern std::ostream* g_swallow_stream;
467
468// Note that g_swallow_stream is used instead of an arbitrary LOG() stream to
469// avoid the creation of an object with a non-trivial destructor (LogMessage).
470// On MSVC x86 (checked on 2015 Update 3), this causes a few additional
471// pointless instructions to be emitted even at full optimization level, even
472// though the : arm of the ternary operator is clearly never executed. Using a
473// simpler object to be &'d with Voidify() avoids these extra instructions.
474// Using a simpler POD object with a templated operator<< also works to avoid
475// these instructions. However, this causes warnings on statically defined
476// implementations of operator<<(std::ostream, ...) in some .cc files, because
477// they become defined-but-unreferenced functions. A reinterpret_cast of 0 to an
478// ostream* also is not suitable, because some compilers warn of undefined
479// behavior.
480#define EAT_STREAM_PARAMETERS \
481 true ? (void)0 \
482 : ::logging::LogMessageVoidify() & (*::logging::g_swallow_stream)
[email protected]ddb9b332011-12-02 07:31:09483
erikwright6ad937b2015-07-22 20:05:52484// Captures the result of a CHECK_EQ (for example) and facilitates testing as a
485// boolean.
486class CheckOpResult {
487 public:
wezf01a9b72016-03-19 01:18:07488 // |message| must be non-null if and only if the check failed.
erikwright6ad937b2015-07-22 20:05:52489 CheckOpResult(std::string* message) : message_(message) {}
490 // Returns true if the check succeeded.
491 operator bool() const { return !message_; }
492 // Returns the message.
493 std::string* message() { return message_; }
494
495 private:
496 std::string* message_;
497};
498
Chris Palmer61343b02016-11-29 20:44:10499// Crashes in the fastest, simplest possible way with no attempt at logging.
scottmga17c8db2017-02-15 21:35:49500#if defined(COMPILER_GCC)
Chris Palmer61343b02016-11-29 20:44:10501#define IMMEDIATE_CRASH() __builtin_trap()
scottmga17c8db2017-02-15 21:35:49502#elif defined(COMPILER_MSVC)
503#define IMMEDIATE_CRASH() __debugbreak()
Chris Palmer61343b02016-11-29 20:44:10504#else
scottmga17c8db2017-02-15 21:35:49505#error Port
Chris Palmer61343b02016-11-29 20:44:10506#endif
507
initial.commitd7cae122008-07-26 21:49:38508// CHECK dies with a fatal error if condition is not true. It is *not*
509// controlled by NDEBUG, so the check will be executed regardless of
510// compilation mode.
[email protected]521b0c42010-10-01 23:02:36511//
512// We make sure CHECK et al. always evaluates their arguments, as
513// doing CHECK(FunctionWithSideEffect()) is a common idiom.
[email protected]ddb9b332011-12-02 07:31:09514
danakjb9d59312016-05-04 20:06:31515#if defined(OFFICIAL_BUILD) && defined(NDEBUG)
[email protected]ddb9b332011-12-02 07:31:09516
Chris Palmer61343b02016-11-29 20:44:10517// Make all CHECK functions discard their log strings to reduce code bloat, and
518// improve performance, for official release builds.
519//
primianoba910a62016-07-07 22:14:48520// This is not calling BreakDebugger since this is called frequently, and
521// calling an out-of-line function instead of a noreturn inline macro prevents
522// compiler optimizations.
Chris Palmer61343b02016-11-29 20:44:10523#define CHECK(condition) \
danakjcb7c5292016-12-20 19:05:35524 UNLIKELY(!(condition)) ? IMMEDIATE_CRASH() : EAT_STREAM_PARAMETERS
[email protected]ddb9b332011-12-02 07:31:09525
526#define PCHECK(condition) CHECK(condition)
527
528#define CHECK_OP(name, op, val1, val2) CHECK((val1) op (val2))
529
danakjb9d59312016-05-04 20:06:31530#else // !(OFFICIAL_BUILD && NDEBUG)
[email protected]ddb9b332011-12-02 07:31:09531
tnagel4a045d3f2015-07-12 14:19:28532// Do as much work as possible out of line to reduce inline code size.
tsniatowski612550f2016-07-21 18:26:20533#define CHECK(condition) \
534 LAZY_STREAM(::logging::LogMessage(__FILE__, __LINE__, #condition).stream(), \
kmarshalle23eed02017-02-11 02:13:23535 !ANALYZER_ASSUME_TRUE(condition))
initial.commitd7cae122008-07-26 21:49:38536
kmarshalle23eed02017-02-11 02:13:23537#define PCHECK(condition) \
538 LAZY_STREAM(PLOG_STREAM(FATAL), !ANALYZER_ASSUME_TRUE(condition)) \
539 << "Check failed: " #condition ". "
brucedawson9d160252014-10-23 20:14:14540
[email protected]ddb9b332011-12-02 07:31:09541// Helper macro for binary operators.
542// Don't use this macro directly in your code, use CHECK_EQ et al below.
erikwright6ad937b2015-07-22 20:05:52543// The 'switch' is used to prevent the 'else' from being ambiguous when the
544// macro is used in an 'if' clause such as:
545// if (a == 1)
546// CHECK_EQ(2, a);
547#define CHECK_OP(name, op, val1, val2) \
548 switch (0) case 0: default: \
tsniatowski612550f2016-07-21 18:26:20549 if (::logging::CheckOpResult true_if_passed = \
550 ::logging::Check##name##Impl((val1), (val2), \
551 #val1 " " #op " " #val2)) \
erikwright6ad937b2015-07-22 20:05:52552 ; \
553 else \
tsniatowski612550f2016-07-21 18:26:20554 ::logging::LogMessage(__FILE__, __LINE__, true_if_passed.message()).stream()
[email protected]ddb9b332011-12-02 07:31:09555
danakjb9d59312016-05-04 20:06:31556#endif // !(OFFICIAL_BUILD && NDEBUG)
[email protected]ddb9b332011-12-02 07:31:09557
brucedawson93a60b8c2016-04-28 20:46:16558// This formats a value for a failing CHECK_XX statement. Ordinarily,
559// it uses the definition for operator<<, with a few special cases below.
560template <typename T>
jbroman6bcfec422016-05-26 00:28:46561inline typename std::enable_if<
raphael.kubo.da.costa81f21202016-11-28 18:36:36562 base::internal::SupportsOstreamOperator<const T&>::value &&
563 !std::is_function<typename std::remove_pointer<T>::type>::value,
jbroman6bcfec422016-05-26 00:28:46564 void>::type
565MakeCheckOpValueString(std::ostream* os, const T& v) {
brucedawson93a60b8c2016-04-28 20:46:16566 (*os) << v;
567}
568
raphael.kubo.da.costa81f21202016-11-28 18:36:36569// Provide an overload for functions and function pointers. Function pointers
570// don't implicitly convert to void* but do implicitly convert to bool, so
571// without this function pointers are always printed as 1 or 0. (MSVC isn't
572// standards-conforming here and converts function pointers to regular
573// pointers, so this is a no-op for MSVC.)
574template <typename T>
575inline typename std::enable_if<
576 std::is_function<typename std::remove_pointer<T>::type>::value,
577 void>::type
578MakeCheckOpValueString(std::ostream* os, const T& v) {
579 (*os) << reinterpret_cast<const void*>(v);
580}
581
jbroman6bcfec422016-05-26 00:28:46582// We need overloads for enums that don't support operator<<.
583// (i.e. scoped enums where no operator<< overload was declared).
584template <typename T>
585inline typename std::enable_if<
586 !base::internal::SupportsOstreamOperator<const T&>::value &&
587 std::is_enum<T>::value,
588 void>::type
589MakeCheckOpValueString(std::ostream* os, const T& v) {
590 (*os) << static_cast<typename base::underlying_type<T>::type>(v);
591}
592
593// We need an explicit overload for std::nullptr_t.
594BASE_EXPORT void MakeCheckOpValueString(std::ostream* os, std::nullptr_t p);
brucedawson93a60b8c2016-04-28 20:46:16595
initial.commitd7cae122008-07-26 21:49:38596// Build the error message string. This is separate from the "Impl"
597// function template because it is not performance critical and so can
[email protected]9c7132e2011-02-08 07:39:08598// be out of line, while the "Impl" code should be inline. Caller
599// takes ownership of the returned string.
initial.commitd7cae122008-07-26 21:49:38600template<class t1, class t2>
601std::string* MakeCheckOpString(const t1& v1, const t2& v2, const char* names) {
602 std::ostringstream ss;
brucedawson93a60b8c2016-04-28 20:46:16603 ss << names << " (";
604 MakeCheckOpValueString(&ss, v1);
605 ss << " vs. ";
606 MakeCheckOpValueString(&ss, v2);
607 ss << ")";
initial.commitd7cae122008-07-26 21:49:38608 std::string* msg = new std::string(ss.str());
609 return msg;
610}
611
[email protected]6d445d32010-09-30 19:10:03612// Commonly used instantiations of MakeCheckOpString<>. Explicitly instantiated
613// in logging.cc.
[email protected]dc72da32011-10-24 20:20:30614extern template BASE_EXPORT std::string* MakeCheckOpString<int, int>(
[email protected]6d445d32010-09-30 19:10:03615 const int&, const int&, const char* names);
[email protected]dc72da32011-10-24 20:20:30616extern template BASE_EXPORT
617std::string* MakeCheckOpString<unsigned long, unsigned long>(
[email protected]6d445d32010-09-30 19:10:03618 const unsigned long&, const unsigned long&, const char* names);
[email protected]dc72da32011-10-24 20:20:30619extern template BASE_EXPORT
620std::string* MakeCheckOpString<unsigned long, unsigned int>(
[email protected]6d445d32010-09-30 19:10:03621 const unsigned long&, const unsigned int&, const char* names);
[email protected]dc72da32011-10-24 20:20:30622extern template BASE_EXPORT
623std::string* MakeCheckOpString<unsigned int, unsigned long>(
[email protected]6d445d32010-09-30 19:10:03624 const unsigned int&, const unsigned long&, const char* names);
[email protected]dc72da32011-10-24 20:20:30625extern template BASE_EXPORT
626std::string* MakeCheckOpString<std::string, std::string>(
[email protected]6d445d32010-09-30 19:10:03627 const std::string&, const std::string&, const char* name);
initial.commitd7cae122008-07-26 21:49:38628
[email protected]71512602010-11-01 22:19:56629// Helper functions for CHECK_OP macro.
630// The (int, int) specialization works around the issue that the compiler
631// will not instantiate the template version of the function on values of
632// unnamed enum type - see comment below.
kmarshall9db26fb2017-02-15 01:05:33633#define DEFINE_CHECK_OP_IMPL(name, op) \
634 template <class t1, class t2> \
635 inline std::string* Check##name##Impl(const t1& v1, const t2& v2, \
636 const char* names) { \
637 if (ANALYZER_ASSUME_TRUE(v1 op v2)) \
638 return NULL; \
639 else \
640 return ::logging::MakeCheckOpString(v1, v2, names); \
641 } \
[email protected]71512602010-11-01 22:19:56642 inline std::string* Check##name##Impl(int v1, int v2, const char* names) { \
kmarshall9db26fb2017-02-15 01:05:33643 if (ANALYZER_ASSUME_TRUE(v1 op v2)) \
644 return NULL; \
645 else \
646 return ::logging::MakeCheckOpString(v1, v2, names); \
[email protected]71512602010-11-01 22:19:56647 }
648DEFINE_CHECK_OP_IMPL(EQ, ==)
649DEFINE_CHECK_OP_IMPL(NE, !=)
650DEFINE_CHECK_OP_IMPL(LE, <=)
651DEFINE_CHECK_OP_IMPL(LT, < )
652DEFINE_CHECK_OP_IMPL(GE, >=)
653DEFINE_CHECK_OP_IMPL(GT, > )
654#undef DEFINE_CHECK_OP_IMPL
[email protected]e150c0382010-03-02 00:41:12655
656#define CHECK_EQ(val1, val2) CHECK_OP(EQ, ==, val1, val2)
657#define CHECK_NE(val1, val2) CHECK_OP(NE, !=, val1, val2)
658#define CHECK_LE(val1, val2) CHECK_OP(LE, <=, val1, val2)
659#define CHECK_LT(val1, val2) CHECK_OP(LT, < , val1, val2)
660#define CHECK_GE(val1, val2) CHECK_OP(GE, >=, val1, val2)
661#define CHECK_GT(val1, val2) CHECK_OP(GT, > , val1, val2)
662
jam121900aa2016-04-19 00:07:34663#if defined(NDEBUG) && !defined(DCHECK_ALWAYS_ON)
danakje649f572015-01-08 23:35:58664#define DCHECK_IS_ON() 0
[email protected]1a1505512014-03-10 18:23:38665#else
danakje649f572015-01-08 23:35:58666#define DCHECK_IS_ON() 1
[email protected]e3cca332009-08-20 01:20:29667#endif
668
[email protected]d15e56c2010-09-30 21:12:33669// Definitions for DLOG et al.
670
gab190f7542016-08-01 20:03:41671#if DCHECK_IS_ON()
[email protected]d926c202010-10-01 02:58:24672
[email protected]5e987802010-11-01 19:49:22673#define DLOG_IS_ON(severity) LOG_IS_ON(severity)
[email protected]d926c202010-10-01 02:58:24674#define DLOG_IF(severity, condition) LOG_IF(severity, condition)
675#define DLOG_ASSERT(condition) LOG_ASSERT(condition)
[email protected]d926c202010-10-01 02:58:24676#define DPLOG_IF(severity, condition) PLOG_IF(severity, condition)
[email protected]521b0c42010-10-01 23:02:36677#define DVLOG_IF(verboselevel, condition) VLOG_IF(verboselevel, condition)
[email protected]fb879b1a2011-03-06 18:16:31678#define DVPLOG_IF(verboselevel, condition) VPLOG_IF(verboselevel, condition)
[email protected]d926c202010-10-01 02:58:24679
gab190f7542016-08-01 20:03:41680#else // DCHECK_IS_ON()
[email protected]d926c202010-10-01 02:58:24681
gab190f7542016-08-01 20:03:41682// If !DCHECK_IS_ON(), we want to avoid emitting any references to |condition|
683// (which may reference a variable defined only if DCHECK_IS_ON()).
684// Contrast this with DCHECK et al., which has different behavior.
[email protected]d926c202010-10-01 02:58:24685
[email protected]5e987802010-11-01 19:49:22686#define DLOG_IS_ON(severity) false
[email protected]ddb9b332011-12-02 07:31:09687#define DLOG_IF(severity, condition) EAT_STREAM_PARAMETERS
688#define DLOG_ASSERT(condition) EAT_STREAM_PARAMETERS
689#define DPLOG_IF(severity, condition) EAT_STREAM_PARAMETERS
690#define DVLOG_IF(verboselevel, condition) EAT_STREAM_PARAMETERS
691#define DVPLOG_IF(verboselevel, condition) EAT_STREAM_PARAMETERS
[email protected]d926c202010-10-01 02:58:24692
gab190f7542016-08-01 20:03:41693#endif // DCHECK_IS_ON()
[email protected]d926c202010-10-01 02:58:24694
gab190f7542016-08-01 20:03:41695// DEBUG_MODE is for runtime uses like
[email protected]d15e56c2010-09-30 21:12:33696// if (DEBUG_MODE) foo.CheckThatFoo();
gab190f7542016-08-01 20:03:41697// We tie its state to DCHECK_IS_ON().
[email protected]d15e56c2010-09-30 21:12:33698//
gab190f7542016-08-01 20:03:41699// For compile-time checks, #if DCHECK_IS_ON() can be used.
700enum { DEBUG_MODE = DCHECK_IS_ON() };
[email protected]d15e56c2010-09-30 21:12:33701
[email protected]521b0c42010-10-01 23:02:36702#define DLOG(severity) \
703 LAZY_STREAM(LOG_STREAM(severity), DLOG_IS_ON(severity))
704
[email protected]521b0c42010-10-01 23:02:36705#define DPLOG(severity) \
706 LAZY_STREAM(PLOG_STREAM(severity), DLOG_IS_ON(severity))
707
[email protected]c3ab11c2011-10-25 06:28:45708#define DVLOG(verboselevel) DVLOG_IF(verboselevel, VLOG_IS_ON(verboselevel))
[email protected]521b0c42010-10-01 23:02:36709
[email protected]fb879b1a2011-03-06 18:16:31710#define DVPLOG(verboselevel) DVPLOG_IF(verboselevel, VLOG_IS_ON(verboselevel))
711
[email protected]521b0c42010-10-01 23:02:36712// Definitions for DCHECK et al.
[email protected]d926c202010-10-01 02:58:24713
danakje649f572015-01-08 23:35:58714#if DCHECK_IS_ON()
[email protected]e3cca332009-08-20 01:20:29715
[email protected]deba0ff2010-11-03 05:30:14716#define COMPACT_GOOGLE_LOG_EX_DCHECK(ClassName, ...) \
717 COMPACT_GOOGLE_LOG_EX_FATAL(ClassName , ##__VA_ARGS__)
718#define COMPACT_GOOGLE_LOG_DCHECK COMPACT_GOOGLE_LOG_FATAL
[email protected]521b0c42010-10-01 23:02:36719const LogSeverity LOG_DCHECK = LOG_FATAL;
720
danakje649f572015-01-08 23:35:58721#else // DCHECK_IS_ON()
[email protected]521b0c42010-10-01 23:02:36722
[email protected]c02cb8012014-03-14 18:39:53723// These are just dummy values.
[email protected]deba0ff2010-11-03 05:30:14724#define COMPACT_GOOGLE_LOG_EX_DCHECK(ClassName, ...) \
725 COMPACT_GOOGLE_LOG_EX_INFO(ClassName , ##__VA_ARGS__)
726#define COMPACT_GOOGLE_LOG_DCHECK COMPACT_GOOGLE_LOG_INFO
727const LogSeverity LOG_DCHECK = LOG_INFO;
[email protected]521b0c42010-10-01 23:02:36728
danakje649f572015-01-08 23:35:58729#endif // DCHECK_IS_ON()
[email protected]521b0c42010-10-01 23:02:36730
[email protected]deba0ff2010-11-03 05:30:14731// DCHECK et al. make sure to reference |condition| regardless of
[email protected]521b0c42010-10-01 23:02:36732// whether DCHECKs are enabled; this is so that we don't get unused
733// variable warnings if the only use of a variable is in a DCHECK.
734// This behavior is different from DLOG_IF et al.
dchengfc670f472017-01-25 17:48:43735//
736// Note that the definition of the DCHECK macros depends on whether or not
737// DCHECK_IS_ON() is true. When DCHECK_IS_ON() is false, the macros use
738// EAT_STREAM_PARAMETERS to avoid expressions that would create temporaries.
[email protected]521b0c42010-10-01 23:02:36739
dchengfc670f472017-01-25 17:48:43740#if DCHECK_IS_ON()
741
kmarshalle23eed02017-02-11 02:13:23742#define DCHECK(condition) \
743 LAZY_STREAM(LOG_STREAM(DCHECK), !ANALYZER_ASSUME_TRUE(condition)) \
dchengfc670f472017-01-25 17:48:43744 << "Check failed: " #condition ". "
kmarshalle23eed02017-02-11 02:13:23745#define DPCHECK(condition) \
746 LAZY_STREAM(PLOG_STREAM(DCHECK), !ANALYZER_ASSUME_TRUE(condition)) \
danakje649f572015-01-08 23:35:58747 << "Check failed: " #condition ". "
[email protected]521b0c42010-10-01 23:02:36748
dchengfc670f472017-01-25 17:48:43749#else // DCHECK_IS_ON()
750
kmarshalle23eed02017-02-11 02:13:23751#define DCHECK(condition) \
752 EAT_STREAM_PARAMETERS << !ANALYZER_ASSUME_TRUE(condition)
753#define DPCHECK(condition) \
754 EAT_STREAM_PARAMETERS << !ANALYZER_ASSUME_TRUE(condition)
dchengfc670f472017-01-25 17:48:43755
756#endif // DCHECK_IS_ON()
[email protected]d926c202010-10-01 02:58:24757
brucedawson9d160252014-10-23 20:14:14758
[email protected]d926c202010-10-01 02:58:24759// Helper macro for binary operators.
760// Don't use this macro directly in your code, use DCHECK_EQ et al below.
erikwright6ad937b2015-07-22 20:05:52761// The 'switch' is used to prevent the 'else' from being ambiguous when the
762// macro is used in an 'if' clause such as:
763// if (a == 1)
764// DCHECK_EQ(2, a);
dchengfc670f472017-01-25 17:48:43765#if DCHECK_IS_ON()
766
tsniatowski612550f2016-07-21 18:26:20767#define DCHECK_OP(name, op, val1, val2) \
768 switch (0) case 0: default: \
769 if (::logging::CheckOpResult true_if_passed = \
770 DCHECK_IS_ON() ? \
771 ::logging::Check##name##Impl((val1), (val2), \
772 #val1 " " #op " " #val2) : nullptr) \
773 ; \
774 else \
775 ::logging::LogMessage(__FILE__, __LINE__, ::logging::LOG_DCHECK, \
776 true_if_passed.message()).stream()
initial.commitd7cae122008-07-26 21:49:38777
dchengfc670f472017-01-25 17:48:43778#else // DCHECK_IS_ON()
779
780// When DCHECKs aren't enabled, DCHECK_OP still needs to reference operator<<
781// overloads for |val1| and |val2| to avoid potential compiler warnings about
782// unused functions. For the same reason, it also compares |val1| and |val2|
783// using |op|.
784//
785// Note that the contract of DCHECK_EQ, etc is that arguments are only evaluated
786// once. Even though |val1| and |val2| appear twice in this version of the macro
787// expansion, this is OK, since the expression is never actually evaluated.
788#define DCHECK_OP(name, op, val1, val2) \
789 EAT_STREAM_PARAMETERS << (::logging::MakeCheckOpValueString( \
790 ::logging::g_swallow_stream, val1), \
791 ::logging::MakeCheckOpValueString( \
792 ::logging::g_swallow_stream, val2), \
kmarshalle23eed02017-02-11 02:13:23793 ANALYZER_ASSUME_TRUE((val1)op(val2)))
dchengfc670f472017-01-25 17:48:43794
795#endif // DCHECK_IS_ON()
796
[email protected]deba0ff2010-11-03 05:30:14797// Equality/Inequality checks - compare two values, and log a
798// LOG_DCHECK message including the two values when the result is not
799// as expected. The values must have operator<<(ostream, ...)
800// defined.
initial.commitd7cae122008-07-26 21:49:38801//
802// You may append to the error message like so:
pwnall7ae42b462016-09-22 02:26:12803// DCHECK_NE(1, 2) << "The world must be ending!";
initial.commitd7cae122008-07-26 21:49:38804//
805// We are very careful to ensure that each argument is evaluated exactly
806// once, and that anything which is legal to pass as a function argument is
807// legal here. In particular, the arguments may be temporary expressions
808// which will end up being destroyed at the end of the apparent statement,
809// for example:
810// DCHECK_EQ(string("abc")[1], 'b');
811//
brucedawson93a60b8c2016-04-28 20:46:16812// WARNING: These don't compile correctly if one of the arguments is a pointer
813// and the other is NULL. In new code, prefer nullptr instead. To
814// work around this for C++98, simply static_cast NULL to the type of the
815// desired pointer.
initial.commitd7cae122008-07-26 21:49:38816
817#define DCHECK_EQ(val1, val2) DCHECK_OP(EQ, ==, val1, val2)
818#define DCHECK_NE(val1, val2) DCHECK_OP(NE, !=, val1, val2)
819#define DCHECK_LE(val1, val2) DCHECK_OP(LE, <=, val1, val2)
820#define DCHECK_LT(val1, val2) DCHECK_OP(LT, < , val1, val2)
821#define DCHECK_GE(val1, val2) DCHECK_OP(GE, >=, val1, val2)
822#define DCHECK_GT(val1, val2) DCHECK_OP(GT, > , val1, val2)
823
danakje649f572015-01-08 23:35:58824#if !DCHECK_IS_ON() && defined(OS_CHROMEOS)
tnagelff3f34a2015-05-24 12:59:14825// Implement logging of NOTREACHED() as a dedicated function to get function
826// call overhead down to a minimum.
827void LogErrorNotReached(const char* file, int line);
828#define NOTREACHED() \
829 true ? ::logging::LogErrorNotReached(__FILE__, __LINE__) \
830 : EAT_STREAM_PARAMETERS
[email protected]7c67fbe2013-09-26 07:55:21831#else
initial.commitd7cae122008-07-26 21:49:38832#define NOTREACHED() DCHECK(false)
[email protected]7c67fbe2013-09-26 07:55:21833#endif
initial.commitd7cae122008-07-26 21:49:38834
835// Redefine the standard assert to use our nice log files
836#undef assert
837#define assert(x) DLOG_ASSERT(x)
838
839// This class more or less represents a particular log message. You
840// create an instance of LogMessage and then stream stuff to it.
841// When you finish streaming to it, ~LogMessage is called and the
842// full message gets streamed to the appropriate destination.
843//
844// You shouldn't actually use LogMessage's constructor to log things,
845// though. You should use the LOG() macro (and variants thereof)
846// above.
[email protected]0bea7252011-08-05 15:34:00847class BASE_EXPORT LogMessage {
initial.commitd7cae122008-07-26 21:49:38848 public:
[email protected]bf8ddf13a2014-06-18 15:02:22849 // Used for LOG(severity).
initial.commitd7cae122008-07-26 21:49:38850 LogMessage(const char* file, int line, LogSeverity severity);
851
tnagel4a045d3f2015-07-12 14:19:28852 // Used for CHECK(). Implied severity = LOG_FATAL.
853 LogMessage(const char* file, int line, const char* condition);
854
[email protected]bf8ddf13a2014-06-18 15:02:22855 // Used for CHECK_EQ(), etc. Takes ownership of the given string.
856 // Implied severity = LOG_FATAL.
[email protected]9c7132e2011-02-08 07:39:08857 LogMessage(const char* file, int line, std::string* result);
initial.commitd7cae122008-07-26 21:49:38858
[email protected]bf8ddf13a2014-06-18 15:02:22859 // Used for DCHECK_EQ(), etc. Takes ownership of the given string.
[email protected]fb62a532009-02-12 01:19:05860 LogMessage(const char* file, int line, LogSeverity severity,
[email protected]9c7132e2011-02-08 07:39:08861 std::string* result);
[email protected]fb62a532009-02-12 01:19:05862
initial.commitd7cae122008-07-26 21:49:38863 ~LogMessage();
864
865 std::ostream& stream() { return stream_; }
866
pastarmovj89f7ee12016-09-20 14:58:13867 LogSeverity severity() { return severity_; }
868 std::string str() { return stream_.str(); }
869
initial.commitd7cae122008-07-26 21:49:38870 private:
871 void Init(const char* file, int line);
872
873 LogSeverity severity_;
874 std::ostringstream stream_;
[email protected]c88873922008-07-30 13:02:03875 size_t message_start_; // Offset of the start of the message (past prefix
876 // info).
[email protected]162ac0f2010-11-04 15:50:49877 // The file and line information passed in to the constructor.
878 const char* file_;
879 const int line_;
880
[email protected]3f85caa2009-04-14 16:52:11881#if defined(OS_WIN)
882 // Stores the current value of GetLastError in the constructor and restores
883 // it in the destructor by calling SetLastError.
884 // This is useful since the LogMessage class uses a lot of Win32 calls
885 // that will lose the value of GLE and the code that called the log function
886 // will have lost the thread error value when the log call returns.
887 class SaveLastError {
888 public:
889 SaveLastError();
890 ~SaveLastError();
891
892 unsigned long get_error() const { return last_error_; }
893
894 protected:
895 unsigned long last_error_;
896 };
897
898 SaveLastError last_error_;
899#endif
initial.commitd7cae122008-07-26 21:49:38900
[email protected]39be4242008-08-07 18:31:40901 DISALLOW_COPY_AND_ASSIGN(LogMessage);
initial.commitd7cae122008-07-26 21:49:38902};
903
initial.commitd7cae122008-07-26 21:49:38904// This class is used to explicitly ignore values in the conditional
905// logging macros. This avoids compiler warnings like "value computed
906// is not used" and "statement has no effect".
[email protected]23bb71f2011-04-21 22:22:10907class LogMessageVoidify {
initial.commitd7cae122008-07-26 21:49:38908 public:
909 LogMessageVoidify() { }
910 // This has to be an operator with a precedence lower than << but
911 // higher than ?:
912 void operator&(std::ostream&) { }
913};
914
[email protected]d8617a62009-10-09 23:52:20915#if defined(OS_WIN)
916typedef unsigned long SystemErrorCode;
917#elif defined(OS_POSIX)
918typedef int SystemErrorCode;
919#endif
920
921// Alias for ::GetLastError() on Windows and errno on POSIX. Avoids having to
922// pull in windows.h just for GetLastError() and DWORD.
[email protected]0bea7252011-08-05 15:34:00923BASE_EXPORT SystemErrorCode GetLastSystemErrorCode();
[email protected]c914d8a2014-04-23 01:11:01924BASE_EXPORT std::string SystemErrorCodeToString(SystemErrorCode error_code);
[email protected]d8617a62009-10-09 23:52:20925
926#if defined(OS_WIN)
927// Appends a formatted system message of the GetLastError() type.
[email protected]0bea7252011-08-05 15:34:00928class BASE_EXPORT Win32ErrorLogMessage {
[email protected]d8617a62009-10-09 23:52:20929 public:
930 Win32ErrorLogMessage(const char* file,
931 int line,
932 LogSeverity severity,
[email protected]d8617a62009-10-09 23:52:20933 SystemErrorCode err);
934
[email protected]d8617a62009-10-09 23:52:20935 // Appends the error message before destructing the encapsulated class.
936 ~Win32ErrorLogMessage();
937
[email protected]a502bbe72011-01-07 18:06:45938 std::ostream& stream() { return log_message_.stream(); }
939
[email protected]d8617a62009-10-09 23:52:20940 private:
941 SystemErrorCode err_;
[email protected]d8617a62009-10-09 23:52:20942 LogMessage log_message_;
943
944 DISALLOW_COPY_AND_ASSIGN(Win32ErrorLogMessage);
945};
946#elif defined(OS_POSIX)
947// Appends a formatted system message of the errno type
[email protected]0bea7252011-08-05 15:34:00948class BASE_EXPORT ErrnoLogMessage {
[email protected]d8617a62009-10-09 23:52:20949 public:
950 ErrnoLogMessage(const char* file,
951 int line,
952 LogSeverity severity,
953 SystemErrorCode err);
954
[email protected]d8617a62009-10-09 23:52:20955 // Appends the error message before destructing the encapsulated class.
956 ~ErrnoLogMessage();
957
[email protected]a502bbe72011-01-07 18:06:45958 std::ostream& stream() { return log_message_.stream(); }
959
[email protected]d8617a62009-10-09 23:52:20960 private:
961 SystemErrorCode err_;
962 LogMessage log_message_;
963
964 DISALLOW_COPY_AND_ASSIGN(ErrnoLogMessage);
965};
966#endif // OS_WIN
967
initial.commitd7cae122008-07-26 21:49:38968// Closes the log file explicitly if open.
969// NOTE: Since the log file is opened as necessary by the action of logging
970// statements, there's no guarantee that it will stay closed
971// after this call.
[email protected]0bea7252011-08-05 15:34:00972BASE_EXPORT void CloseLogFile();
initial.commitd7cae122008-07-26 21:49:38973
[email protected]e36ddc82009-12-08 04:22:50974// Async signal safe logging mechanism.
[email protected]0bea7252011-08-05 15:34:00975BASE_EXPORT void RawLog(int level, const char* message);
[email protected]e36ddc82009-12-08 04:22:50976
tsniatowski612550f2016-07-21 18:26:20977#define RAW_LOG(level, message) \
978 ::logging::RawLog(::logging::LOG_##level, message)
[email protected]e36ddc82009-12-08 04:22:50979
tsniatowski612550f2016-07-21 18:26:20980#define RAW_CHECK(condition) \
981 do { \
kmarshalle23eed02017-02-11 02:13:23982 if (!ANALYZER_ASSUME_TRUE(condition)) \
tsniatowski612550f2016-07-21 18:26:20983 ::logging::RawLog(::logging::LOG_FATAL, \
984 "Check failed: " #condition "\n"); \
[email protected]e36ddc82009-12-08 04:22:50985 } while (0)
986
[email protected]f01b88a2013-02-27 22:04:00987#if defined(OS_WIN)
ananta61762fb2015-09-18 01:00:09988// Returns true if logging to file is enabled.
989BASE_EXPORT bool IsLoggingToFileEnabled();
990
[email protected]f01b88a2013-02-27 22:04:00991// Returns the default log file path.
992BASE_EXPORT std::wstring GetLogFileFullPath();
993#endif
994
[email protected]39be4242008-08-07 18:31:40995} // namespace logging
initial.commitd7cae122008-07-26 21:49:38996
[email protected]81411c62014-07-08 23:03:06997// Note that "The behavior of a C++ program is undefined if it adds declarations
998// or definitions to namespace std or to a namespace within namespace std unless
999// otherwise specified." --C++11[namespace.std]
1000//
1001// We've checked that this particular definition has the intended behavior on
1002// our implementations, but it's prone to breaking in the future, and please
1003// don't imitate this in your own definitions without checking with some
1004// standard library experts.
1005namespace std {
[email protected]46ce5b562010-06-16 18:39:531006// These functions are provided as a convenience for logging, which is where we
1007// use streams (it is against Google style to use streams in other places). It
1008// is designed to allow you to emit non-ASCII Unicode strings to the log file,
1009// which is normally ASCII. It is relatively slow, so try not to use it for
1010// common cases. Non-ASCII characters will be converted to UTF-8 by these
1011// operators.
[email protected]0bea7252011-08-05 15:34:001012BASE_EXPORT std::ostream& operator<<(std::ostream& out, const wchar_t* wstr);
[email protected]46ce5b562010-06-16 18:39:531013inline std::ostream& operator<<(std::ostream& out, const std::wstring& wstr) {
1014 return out << wstr.c_str();
1015}
[email protected]81411c62014-07-08 23:03:061016} // namespace std
[email protected]46ce5b562010-06-16 18:39:531017
[email protected]0dfc81b2008-08-25 03:44:401018// The NOTIMPLEMENTED() macro annotates codepaths which have
1019// not been implemented yet.
1020//
1021// The implementation of this macro is controlled by NOTIMPLEMENTED_POLICY:
1022// 0 -- Do nothing (stripped by compiler)
1023// 1 -- Warn at compile time
1024// 2 -- Fail at compile time
1025// 3 -- Fail at runtime (DCHECK)
1026// 4 -- [default] LOG(ERROR) at runtime
1027// 5 -- LOG(ERROR) at runtime, only once per call-site
1028
1029#ifndef NOTIMPLEMENTED_POLICY
[email protected]f5c7758a2012-07-25 16:17:571030#if defined(OS_ANDROID) && defined(OFFICIAL_BUILD)
1031#define NOTIMPLEMENTED_POLICY 0
1032#else
[email protected]0dfc81b2008-08-25 03:44:401033// Select default policy: LOG(ERROR)
1034#define NOTIMPLEMENTED_POLICY 4
1035#endif
[email protected]f5c7758a2012-07-25 16:17:571036#endif
[email protected]0dfc81b2008-08-25 03:44:401037
[email protected]f6cda752008-10-30 23:54:261038#if defined(COMPILER_GCC)
1039// On Linux, with GCC, we can use __PRETTY_FUNCTION__ to get the demangled name
1040// of the current function in the NOTIMPLEMENTED message.
1041#define NOTIMPLEMENTED_MSG "Not implemented reached in " << __PRETTY_FUNCTION__
1042#else
1043#define NOTIMPLEMENTED_MSG "NOT IMPLEMENTED"
1044#endif
1045
[email protected]0dfc81b2008-08-25 03:44:401046#if NOTIMPLEMENTED_POLICY == 0
[email protected]38227292012-01-30 19:41:541047#define NOTIMPLEMENTED() EAT_STREAM_PARAMETERS
[email protected]0dfc81b2008-08-25 03:44:401048#elif NOTIMPLEMENTED_POLICY == 1
1049// TODO, figure out how to generate a warning
avi4ec0dff2015-11-24 14:26:241050#define NOTIMPLEMENTED() static_assert(false, "NOT_IMPLEMENTED")
[email protected]0dfc81b2008-08-25 03:44:401051#elif NOTIMPLEMENTED_POLICY == 2
avi4ec0dff2015-11-24 14:26:241052#define NOTIMPLEMENTED() static_assert(false, "NOT_IMPLEMENTED")
[email protected]0dfc81b2008-08-25 03:44:401053#elif NOTIMPLEMENTED_POLICY == 3
1054#define NOTIMPLEMENTED() NOTREACHED()
1055#elif NOTIMPLEMENTED_POLICY == 4
[email protected]f6cda752008-10-30 23:54:261056#define NOTIMPLEMENTED() LOG(ERROR) << NOTIMPLEMENTED_MSG
[email protected]0dfc81b2008-08-25 03:44:401057#elif NOTIMPLEMENTED_POLICY == 5
1058#define NOTIMPLEMENTED() do {\
[email protected]b70ff012013-02-13 08:32:141059 static bool logged_once = false;\
1060 LOG_IF(ERROR, !logged_once) << NOTIMPLEMENTED_MSG;\
1061 logged_once = true;\
1062} while(0);\
1063EAT_STREAM_PARAMETERS
[email protected]0dfc81b2008-08-25 03:44:401064#endif
1065
[email protected]39be4242008-08-07 18:31:401066#endif // BASE_LOGGING_H_