[go: nahoru, domu]

blob: e3af43ae47d02f24478c0e9c1292f0617e4d1d8e [file] [log] [blame]
akalin@chromium.org34a907732012-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
brettw@google.com39be4242008-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
tzik@chromium.orge7972d12011-06-18 11:53:1410#include <cassert>
Sharon Yang7cb919a2019-05-20 20:27:1511#include <cstdint>
initial.commitd7cae122008-07-26 21:49:3812#include <cstring>
13#include <sstream>
avi9b6f42932015-12-26 22:15:1414#include <string>
jbroman6bcfec422016-05-26 00:28:4615#include <type_traits>
16#include <utility>
initial.commitd7cae122008-07-26 21:49:3817
darin@chromium.org0bea7252011-08-05 15:34:0018#include "base/base_export.h"
alex-accc1bde62017-04-19 08:33:5519#include "base/callback_forward.h"
danakjcb7c5292016-12-20 19:05:3520#include "base/compiler_specific.h"
Daniel Chenged0471b2019-05-10 11:43:3621#include "base/immediate_crash.h"
Xiaohan Wangee536b212019-05-07 16:16:0722#include "base/logging_buildflags.h"
avi9b6f42932015-12-26 22:15:1423#include "base/macros.h"
Etienne Pierre-Dorayd120ebf2018-09-14 23:38:2124#include "base/scoped_clear_last_error.h"
alex-accc1bde62017-04-19 08:33:5525#include "base/strings/string_piece_forward.h"
jbroman6bcfec422016-05-26 00:28:4626#include "base/template_util.h"
rvargas@google.com90509cb2011-03-25 18:46:3827#include "build/build_config.h"
initial.commitd7cae122008-07-26 21:49:3828
29//
30// Optional message capabilities
31// -----------------------------
32// Assertion failed messages and fatal errors are displayed in a dialog box
33// before the application exits. However, running this UI creates a message
34// loop, which causes application messages to be processed and potentially
35// dispatched to existing application windows. Since the application is in a
36// bad state when this assertion dialog is displayed, these messages may not
37// get processed and hang the dialog, or the application might go crazy.
38//
39// Therefore, it can be beneficial to display the error dialog in a separate
40// process from the main application. When the logging system needs to display
41// a fatal error dialog box, it will look for a program called
42// "DebugMessage.exe" in the same directory as the application executable. It
43// will run this application with the message as the command line, and will
44// not include the name of the application as is traditional for easier
45// parsing.
46//
47// The code for DebugMessage.exe is only one line. In WinMain, do:
48// MessageBox(NULL, GetCommandLineW(), L"Fatal Error", 0);
49//
50// If DebugMessage.exe is not found, the logging code will use a normal
51// MessageBox, potentially causing the problems discussed above.
52
initial.commitd7cae122008-07-26 21:49:3853// Instructions
54// ------------
55//
56// Make a bunch of macros for logging. The way to log things is to stream
57// things to LOG(<a particular severity level>). E.g.,
58//
59// LOG(INFO) << "Found " << num_cookies << " cookies";
60//
61// You can also do conditional logging:
62//
63// LOG_IF(INFO, num_cookies > 10) << "Got lots of cookies";
64//
initial.commitd7cae122008-07-26 21:49:3865// The CHECK(condition) macro is active in both debug and release builds and
66// effectively performs a LOG(FATAL) which terminates the process and
67// generates a crashdump unless a debugger is attached.
68//
69// There are also "debug mode" logging macros like the ones above:
70//
71// DLOG(INFO) << "Found cookies";
72//
73// DLOG_IF(INFO, num_cookies > 10) << "Got lots of cookies";
74//
75// All "debug mode" logging is compiled away to nothing for non-debug mode
76// compiles. LOG_IF and development flags also work well together
77// because the code can be compiled away sometimes.
78//
79// We also have
80//
81// LOG_ASSERT(assertion);
82// DLOG_ASSERT(assertion);
83//
84// which is syntactic sugar for {,D}LOG_IF(FATAL, assert fails) << assertion;
85//
akalin@chromium.org99b7c57f2010-09-29 19:26:3686// There are "verbose level" logging macros. They look like
87//
88// VLOG(1) << "I'm printed when you run the program with --v=1 or more";
89// VLOG(2) << "I'm printed when you run the program with --v=2 or more";
90//
91// These always log at the INFO log level (when they log at all).
92// The verbose logging can also be turned on module-by-module. For instance,
akalin@chromium.orgb0d38d4c2010-10-29 00:39:4893// --vmodule=profile=2,icon_loader=1,browser_*=3,*/chromeos/*=4 --v=0
akalin@chromium.org99b7c57f2010-09-29 19:26:3694// will cause:
95// a. VLOG(2) and lower messages to be printed from profile.{h,cc}
96// b. VLOG(1) and lower messages to be printed from icon_loader.{h,cc}
97// c. VLOG(3) and lower messages to be printed from files prefixed with
98// "browser"
akalin@chromium.orge11de722010-11-01 20:50:5599// d. VLOG(4) and lower messages to be printed from files under a
akalin@chromium.orgb0d38d4c2010-10-29 00:39:48100// "chromeos" directory.
akalin@chromium.orge11de722010-11-01 20:50:55101// e. VLOG(0) and lower messages to be printed from elsewhere
akalin@chromium.org99b7c57f2010-09-29 19:26:36102//
103// The wildcarding functionality shown by (c) supports both '*' (match
akalin@chromium.orgb0d38d4c2010-10-29 00:39:48104// 0 or more characters) and '?' (match any single character)
105// wildcards. Any pattern containing a forward or backward slash will
106// be tested against the whole pathname and not just the module.
107// E.g., "*/foo/bar/*=2" would change the logging level for all code
108// in source files under a "foo/bar" directory.
akalin@chromium.org99b7c57f2010-09-29 19:26:36109//
110// There's also VLOG_IS_ON(n) "verbose level" condition macro. To be used as
111//
112// if (VLOG_IS_ON(2)) {
113// // do some logging preparation and logging
114// // that can't be accomplished with just VLOG(2) << ...;
115// }
116//
117// There is also a VLOG_IF "verbose level" condition macro for sample
118// cases, when some extra computation and preparation for logs is not
119// needed.
120//
121// VLOG_IF(1, (size > 1024))
122// << "I'm printed when size is more than 1024 and when you run the "
123// "program with --v=1 or more";
124//
initial.commitd7cae122008-07-26 21:49:38125// We also override the standard 'assert' to use 'DLOG_ASSERT'.
126//
tschmelcher@chromium.orgd8617a62009-10-09 23:52:20127// Lastly, there is:
128//
129// PLOG(ERROR) << "Couldn't do foo";
130// DPLOG(ERROR) << "Couldn't do foo";
131// PLOG_IF(ERROR, cond) << "Couldn't do foo";
132// DPLOG_IF(ERROR, cond) << "Couldn't do foo";
133// PCHECK(condition) << "Couldn't do foo";
134// DPCHECK(condition) << "Couldn't do foo";
135//
136// which append the last system error to the message in string form (taken from
137// GetLastError() on Windows and errno on POSIX).
138//
initial.commitd7cae122008-07-26 21:49:38139// The supported severity levels for macros that allow you to specify one
viettrungluu@chromium.orgf2c05492014-06-17 12:04:23140// are (in increasing order of severity) INFO, WARNING, ERROR, and FATAL.
initial.commitd7cae122008-07-26 21:49:38141//
142// Very important: logging a message at the FATAL severity level causes
143// the program to terminate (after the message is logged).
huanr@chromium.orgfb62a532009-02-12 01:19:05144//
viettrungluu@chromium.orgf2c05492014-06-17 12:04:23145// There is the special severity of DFATAL, which logs FATAL in debug mode,
146// ERROR in normal mode.
Rob Schonberger45637212018-12-03 04:46:25147//
148// Output is of the format, for example:
149// [3816:3877:0812/234555.406952:VERBOSE1:drm_device_handle.cc(90)] Succeeded
150// authenticating /dev/dri/card0 in 0 ms with 1 attempt(s)
151//
152// The colon separated fields inside the brackets are as follows:
153// 0. An optional Logfile prefix (not included in this example)
154// 1. Process ID
155// 2. Thread ID
156// 3. The date/time of the log message, in MMDD/HHMMSS.Milliseconds format
157// 4. The log level
158// 5. The filename and line number where the log was instantiated
159//
160// Note that the visibility can be changed by setting preferences in
161// SetLogItems()
initial.commitd7cae122008-07-26 21:49:38162
163namespace logging {
164
akalin@chromium.org5e3f7c22013-06-21 21:15:33165// TODO(avi): do we want to do a unification of character types here?
166#if defined(OS_WIN)
jdoerrie5c4dc4e2019-02-01 18:02:33167typedef base::char16 PathChar;
Fabrice de Gans-Riberi306871de2018-05-16 19:38:39168#elif defined(OS_POSIX) || defined(OS_FUCHSIA)
akalin@chromium.org5e3f7c22013-06-21 21:15:33169typedef char PathChar;
170#endif
171
Sharon Yang7cb919a2019-05-20 20:27:15172// A bitmask of potential logging destinations.
173using LoggingDestination = uint32_t;
174// Specifies where logs will be written. Multiple destinations can be specified
175// with bitwise OR.
176// Unless destination is LOG_NONE, all logs with severity ERROR and above will
177// be written to stderr in addition to the specified destination.
178enum : uint32_t {
akalin@chromium.org5e3f7c22013-06-21 21:15:33179 LOG_NONE = 0,
180 LOG_TO_FILE = 1 << 0,
181 LOG_TO_SYSTEM_DEBUG_LOG = 1 << 1,
Sharon Yang7cb919a2019-05-20 20:27:15182 LOG_TO_STDERR = 1 << 2,
akalin@chromium.org5e3f7c22013-06-21 21:15:33183
Sharon Yang7cb919a2019-05-20 20:27:15184 LOG_TO_ALL = LOG_TO_FILE | LOG_TO_SYSTEM_DEBUG_LOG | LOG_TO_STDERR,
akalin@chromium.org5e3f7c22013-06-21 21:15:33185
Sharon Yang7cb919a2019-05-20 20:27:15186// On Windows, use a file next to the exe.
187// On POSIX platforms, where it may not even be possible to locate the
188// executable on disk, use stderr.
189// On Fuchsia, use the Fuchsia logging service.
190#if defined(OS_FUCHSIA) || defined(OS_NACL)
akalin@chromium.org5e3f7c22013-06-21 21:15:33191 LOG_DEFAULT = LOG_TO_SYSTEM_DEBUG_LOG,
Sharon Yang7cb919a2019-05-20 20:27:15192#elif defined(OS_WIN)
193 LOG_DEFAULT = LOG_TO_FILE,
194#elif defined(OS_POSIX)
195 LOG_DEFAULT = LOG_TO_SYSTEM_DEBUG_LOG | LOG_TO_STDERR,
akalin@chromium.org5e3f7c22013-06-21 21:15:33196#endif
197};
initial.commitd7cae122008-07-26 21:49:38198
199// Indicates that the log file should be locked when being written to.
akalin@chromium.org5e3f7c22013-06-21 21:15:33200// Unless there is only one single-threaded process that is logging to
201// the log file, the file should be locked during writes to make each
wangxianzhu@chromium.org3ee50d12014-03-05 01:43:27202// log output atomic. Other writers will block.
initial.commitd7cae122008-07-26 21:49:38203//
204// All processes writing to the log file must have their locking set for it to
akalin@chromium.org5e3f7c22013-06-21 21:15:33205// work properly. Defaults to LOCK_LOG_FILE.
initial.commitd7cae122008-07-26 21:49:38206enum LogLockingState { LOCK_LOG_FILE, DONT_LOCK_LOG_FILE };
207
208// On startup, should we delete or append to an existing log file (if any)?
209// Defaults to APPEND_TO_OLD_LOG_FILE.
210enum OldFileDeletionState { DELETE_OLD_LOG_FILE, APPEND_TO_OLD_LOG_FILE };
211
akalin@chromium.org5e3f7c22013-06-21 21:15:33212struct BASE_EXPORT LoggingSettings {
Sharon Yang7cb919a2019-05-20 20:27:15213 // Equivalent to logging destination enum, but allows for multiple
214 // destinations.
Wez7e125622019-05-29 22:11:28215 uint32_t logging_dest = LOG_DEFAULT;
akalin@chromium.org5e3f7c22013-06-21 21:15:33216
217 // The three settings below have an effect only when LOG_TO_FILE is
218 // set in |logging_dest|.
Wez7e125622019-05-29 22:11:28219 const PathChar* log_file = nullptr;
220 LogLockingState lock_log = LOCK_LOG_FILE;
221 OldFileDeletionState delete_old = APPEND_TO_OLD_LOG_FILE;
akalin@chromium.org5e3f7c22013-06-21 21:15:33222};
derat@chromium.orgff3d0c32010-08-23 19:57:46223
224// Define different names for the BaseInitLoggingImpl() function depending on
225// whether NDEBUG is defined or not so that we'll fail to link if someone tries
226// to compile logging.cc with NDEBUG but includes logging.h without defining it,
227// or vice versa.
weza245bd072017-06-18 23:26:34228#if defined(NDEBUG)
derat@chromium.orgff3d0c32010-08-23 19:57:46229#define BaseInitLoggingImpl BaseInitLoggingImpl_built_with_NDEBUG
230#else
231#define BaseInitLoggingImpl BaseInitLoggingImpl_built_without_NDEBUG
232#endif
233
234// Implementation of the InitLogging() method declared below. We use a
235// more-specific name so we can #define it above without affecting other code
236// that has named stuff "InitLogging".
akalin@chromium.org5e3f7c22013-06-21 21:15:33237BASE_EXPORT bool BaseInitLoggingImpl(const LoggingSettings& settings);
derat@chromium.orgff3d0c32010-08-23 19:57:46238
initial.commitd7cae122008-07-26 21:49:38239// Sets the log file name and other global logging state. Calling this function
240// is recommended, and is normally done at the beginning of application init.
241// If you don't call it, all the flags will be initialized to their default
242// values, and there is a race condition that may leak a critical section
243// object if two threads try to do the first log at the same time.
244// See the definition of the enums above for descriptions and default values.
245//
246// The default log file is initialized to "debug.log" in the application
247// directory. You probably don't want this, especially since the program
248// directory may not be writable on an enduser's system.
stevenjb@chromium.org064aa162011-12-03 00:30:08249//
250// This function may be called a second time to re-direct logging (e.g after
251// loging in to a user partition), however it should never be called more than
252// twice.
akalin@chromium.org5e3f7c22013-06-21 21:15:33253inline bool InitLogging(const LoggingSettings& settings) {
254 return BaseInitLoggingImpl(settings);
derat@chromium.orgff3d0c32010-08-23 19:57:46255}
initial.commitd7cae122008-07-26 21:49:38256
257// Sets the log level. Anything at or above this level will be written to the
258// log file/displayed to the user (if applicable). Anything below this level
siggi@chromium.org162ac0f2010-11-04 15:50:49259// will be silently ignored. The log level defaults to 0 (everything is logged
260// up to level INFO) if this function is not called.
261// Note that log messages for VLOG(x) are logged at level -x, so setting
262// the min log level to negative values enables verbose logging.
darin@chromium.org0bea7252011-08-05 15:34:00263BASE_EXPORT void SetMinLogLevel(int level);
initial.commitd7cae122008-07-26 21:49:38264
ericroman@google.com8a2986ca2009-04-10 19:13:42265// Gets the current log level.
darin@chromium.org0bea7252011-08-05 15:34:00266BASE_EXPORT int GetMinLogLevel();
initial.commitd7cae122008-07-26 21:49:38267
skobesc78c0ad72015-12-07 20:21:23268// Used by LOG_IS_ON to lazy-evaluate stream arguments.
269BASE_EXPORT bool ShouldCreateLogMessage(int severity);
270
siggi@chromium.org162ac0f2010-11-04 15:50:49271// Gets the VLOG default verbosity level.
darin@chromium.org0bea7252011-08-05 15:34:00272BASE_EXPORT int GetVlogVerbosity();
siggi@chromium.org162ac0f2010-11-04 15:50:49273
akalin@chromium.org2f4e9a62010-09-29 21:25:14274// Note that |N| is the size *with* the null terminator.
darin@chromium.org0bea7252011-08-05 15:34:00275BASE_EXPORT int GetVlogLevelHelper(const char* file_start, size_t N);
akalin@chromium.org2f4e9a62010-09-29 21:25:14276
tnagel270da922017-05-24 12:10:44277// Gets the current vlog level for the given file (usually taken from __FILE__).
akalin@chromium.org99b7c57f2010-09-29 19:26:36278template <size_t N>
279int GetVlogLevel(const char (&file)[N]) {
280 return GetVlogLevelHelper(file, N);
281}
initial.commitd7cae122008-07-26 21:49:38282
283// Sets the common items you want to be prepended to each log message.
284// process and thread IDs default to off, the timestamp defaults to on.
285// If this function is not called, logging defaults to writing the timestamp
286// only.
darin@chromium.org0bea7252011-08-05 15:34:00287BASE_EXPORT void SetLogItems(bool enable_process_id, bool enable_thread_id,
288 bool enable_timestamp, bool enable_tickcount);
initial.commitd7cae122008-07-26 21:49:38289
James Cooka0536c32018-08-01 20:13:31290// Sets an optional prefix to add to each log message. |prefix| is not copied
291// and should be a raw string constant. |prefix| must only contain ASCII letters
292// to avoid confusion with PIDs and timestamps. Pass null to remove the prefix.
293// Logging defaults to no prefix.
294BASE_EXPORT void SetLogPrefix(const char* prefix);
295
cmasone@google.com81e0a852010-08-17 00:38:12296// Sets whether or not you'd like to see fatal debug messages popped up in
297// a dialog box or not.
298// Dialogs are not shown by default.
darin@chromium.org0bea7252011-08-05 15:34:00299BASE_EXPORT void SetShowErrorDialogs(bool enable_dialogs);
cmasone@google.com81e0a852010-08-17 00:38:12300
initial.commitd7cae122008-07-26 21:49:38301// Sets the Log Assert Handler that will be used to notify of check failures.
alex-accc1bde62017-04-19 08:33:55302// Resets Log Assert Handler on object destruction.
huanr@chromium.orgfb62a532009-02-12 01:19:05303// The default handler shows a dialog box and then terminate the process,
304// however clients can use this function to override with their own handling
305// (e.g. a silent one for Unit Tests)
alex-accc1bde62017-04-19 08:33:55306using LogAssertHandlerFunction =
kylechar83fb51e52019-03-14 15:30:43307 base::RepeatingCallback<void(const char* file,
308 int line,
309 const base::StringPiece message,
310 const base::StringPiece stack_trace)>;
alex-accc1bde62017-04-19 08:33:55311
312class BASE_EXPORT ScopedLogAssertHandler {
313 public:
314 explicit ScopedLogAssertHandler(LogAssertHandlerFunction handler);
315 ~ScopedLogAssertHandler();
316
317 private:
318 DISALLOW_COPY_AND_ASSIGN(ScopedLogAssertHandler);
319};
hansl@google.com64e5cc02010-11-03 19:20:27320
siggi@chromium.org2b07b8412009-11-25 15:26:34321// Sets the Log Message Handler that gets passed every log message before
322// it's sent to other log destinations (if any).
323// Returns true to signal that it handled the message and the message
324// should not be sent to other log destinations.
siggi@chromium.org162ac0f2010-11-04 15:50:49325typedef bool (*LogMessageHandlerFunction)(int severity,
326 const char* file, int line, size_t message_start, const std::string& str);
darin@chromium.org0bea7252011-08-05 15:34:00327BASE_EXPORT void SetLogMessageHandler(LogMessageHandlerFunction handler);
328BASE_EXPORT LogMessageHandlerFunction GetLogMessageHandler();
siggi@chromium.org2b07b8412009-11-25 15:26:34329
kmarshallfe2f09f82017-04-20 21:05:26330// The ANALYZER_ASSUME_TRUE(bool arg) macro adds compiler-specific hints
331// to Clang which control what code paths are statically analyzed,
332// and is meant to be used in conjunction with assert & assert-like functions.
333// The expression is passed straight through if analysis isn't enabled.
Kevin Marshall7273edd2017-06-20 22:19:36334//
335// ANALYZER_SKIP_THIS_PATH() suppresses static analysis for the current
336// codepath and any other branching codepaths that might follow.
kmarshallfe2f09f82017-04-20 21:05:26337#if defined(__clang_analyzer__)
338
339inline constexpr bool AnalyzerNoReturn() __attribute__((analyzer_noreturn)) {
340 return false;
341}
342
343inline constexpr bool AnalyzerAssumeTrue(bool arg) {
344 // AnalyzerNoReturn() is invoked and analysis is terminated if |arg| is
345 // false.
346 return arg || AnalyzerNoReturn();
347}
348
Kevin Marshall7273edd2017-06-20 22:19:36349#define ANALYZER_ASSUME_TRUE(arg) logging::AnalyzerAssumeTrue(!!(arg))
350#define ANALYZER_SKIP_THIS_PATH() \
351 static_cast<void>(::logging::AnalyzerNoReturn())
Kevin Marshall089565ec2017-07-13 02:57:21352#define ANALYZER_ALLOW_UNUSED(var) static_cast<void>(var);
kmarshallfe2f09f82017-04-20 21:05:26353
354#else // !defined(__clang_analyzer__)
355
356#define ANALYZER_ASSUME_TRUE(arg) (arg)
Kevin Marshall7273edd2017-06-20 22:19:36357#define ANALYZER_SKIP_THIS_PATH()
Kevin Marshall089565ec2017-07-13 02:57:21358#define ANALYZER_ALLOW_UNUSED(var) static_cast<void>(var);
kmarshallfe2f09f82017-04-20 21:05:26359
360#endif // defined(__clang_analyzer__)
361
initial.commitd7cae122008-07-26 21:49:38362typedef int LogSeverity;
siggi@chromium.org162ac0f2010-11-04 15:50:49363const LogSeverity LOG_VERBOSE = -1; // This is level 1 verbosity
364// Note: the log severities are used to index into the array of names,
365// see log_severity_names.
initial.commitd7cae122008-07-26 21:49:38366const LogSeverity LOG_INFO = 0;
367const LogSeverity LOG_WARNING = 1;
368const LogSeverity LOG_ERROR = 2;
viettrungluu@chromium.orgf2c05492014-06-17 12:04:23369const LogSeverity LOG_FATAL = 3;
370const LogSeverity LOG_NUM_SEVERITIES = 4;
initial.commitd7cae122008-07-26 21:49:38371
akalin@chromium.org521b0c42010-10-01 23:02:36372// LOG_DFATAL is LOG_FATAL in debug mode, ERROR in normal mode
weza245bd072017-06-18 23:26:34373#if defined(NDEBUG)
akalin@chromium.org521b0c42010-10-01 23:02:36374const LogSeverity LOG_DFATAL = LOG_ERROR;
initial.commitd7cae122008-07-26 21:49:38375#else
akalin@chromium.org521b0c42010-10-01 23:02:36376const LogSeverity LOG_DFATAL = LOG_FATAL;
initial.commitd7cae122008-07-26 21:49:38377#endif
378
379// A few definitions of macros that don't generate much code. These are used
380// by LOG() and LOG_IF, etc. Since these are used all over our code, it's
381// better to have compact code for these operations.
tschmelcher@chromium.orgd8617a62009-10-09 23:52:20382#define COMPACT_GOOGLE_LOG_EX_INFO(ClassName, ...) \
tsniatowski612550f2016-07-21 18:26:20383 ::logging::ClassName(__FILE__, __LINE__, ::logging::LOG_INFO, ##__VA_ARGS__)
384#define COMPACT_GOOGLE_LOG_EX_WARNING(ClassName, ...) \
385 ::logging::ClassName(__FILE__, __LINE__, ::logging::LOG_WARNING, \
386 ##__VA_ARGS__)
tschmelcher@chromium.orgd8617a62009-10-09 23:52:20387#define COMPACT_GOOGLE_LOG_EX_ERROR(ClassName, ...) \
tsniatowski612550f2016-07-21 18:26:20388 ::logging::ClassName(__FILE__, __LINE__, ::logging::LOG_ERROR, ##__VA_ARGS__)
tschmelcher@chromium.orgd8617a62009-10-09 23:52:20389#define COMPACT_GOOGLE_LOG_EX_FATAL(ClassName, ...) \
tsniatowski612550f2016-07-21 18:26:20390 ::logging::ClassName(__FILE__, __LINE__, ::logging::LOG_FATAL, ##__VA_ARGS__)
tschmelcher@chromium.orgd8617a62009-10-09 23:52:20391#define COMPACT_GOOGLE_LOG_EX_DFATAL(ClassName, ...) \
tsniatowski612550f2016-07-21 18:26:20392 ::logging::ClassName(__FILE__, __LINE__, ::logging::LOG_DFATAL, ##__VA_ARGS__)
Wez289477f2017-08-24 20:51:30393#define COMPACT_GOOGLE_LOG_EX_DCHECK(ClassName, ...) \
394 ::logging::ClassName(__FILE__, __LINE__, ::logging::LOG_DCHECK, ##__VA_ARGS__)
tschmelcher@chromium.orgd8617a62009-10-09 23:52:20395
Wez289477f2017-08-24 20:51:30396#define COMPACT_GOOGLE_LOG_INFO COMPACT_GOOGLE_LOG_EX_INFO(LogMessage)
397#define COMPACT_GOOGLE_LOG_WARNING COMPACT_GOOGLE_LOG_EX_WARNING(LogMessage)
398#define COMPACT_GOOGLE_LOG_ERROR COMPACT_GOOGLE_LOG_EX_ERROR(LogMessage)
399#define COMPACT_GOOGLE_LOG_FATAL COMPACT_GOOGLE_LOG_EX_FATAL(LogMessage)
400#define COMPACT_GOOGLE_LOG_DFATAL COMPACT_GOOGLE_LOG_EX_DFATAL(LogMessage)
401#define COMPACT_GOOGLE_LOG_DCHECK COMPACT_GOOGLE_LOG_EX_DCHECK(LogMessage)
initial.commitd7cae122008-07-26 21:49:38402
joth@chromium.org8d127302013-01-10 02:41:57403#if defined(OS_WIN)
initial.commitd7cae122008-07-26 21:49:38404// wingdi.h defines ERROR to be 0. When we call LOG(ERROR), it gets
405// substituted with 0, and it expands to COMPACT_GOOGLE_LOG_0. To allow us
406// to keep using this syntax, we define this macro to do the same thing
407// as COMPACT_GOOGLE_LOG_ERROR, and also define ERROR the same way that
408// the Windows SDK does for consistency.
409#define ERROR 0
tschmelcher@chromium.orgd8617a62009-10-09 23:52:20410#define COMPACT_GOOGLE_LOG_EX_0(ClassName, ...) \
411 COMPACT_GOOGLE_LOG_EX_ERROR(ClassName , ##__VA_ARGS__)
412#define COMPACT_GOOGLE_LOG_0 COMPACT_GOOGLE_LOG_ERROR
akalin@chromium.org521b0c42010-10-01 23:02:36413// Needed for LOG_IS_ON(ERROR).
414const LogSeverity LOG_0 = LOG_ERROR;
joth@chromium.org8d127302013-01-10 02:41:57415#endif
akalin@chromium.org521b0c42010-10-01 23:02:36416
viettrungluu@chromium.orgf2c05492014-06-17 12:04:23417// As special cases, we can assume that LOG_IS_ON(FATAL) always holds. Also,
418// LOG_IS_ON(DFATAL) always holds in debug mode. In particular, CHECK()s will
419// always fire if they fail.
akalin@chromium.org521b0c42010-10-01 23:02:36420#define LOG_IS_ON(severity) \
skobesc78c0ad72015-12-07 20:21:23421 (::logging::ShouldCreateLogMessage(::logging::LOG_##severity))
akalin@chromium.org521b0c42010-10-01 23:02:36422
Ken MacKay70e8867002019-01-16 00:22:15423// We don't do any caching tricks with VLOG_IS_ON() like the
424// google-glog version since it increases binary size. This means
akalin@chromium.org521b0c42010-10-01 23:02:36425// that using the v-logging functions in conjunction with --vmodule
426// may be slow.
427#define VLOG_IS_ON(verboselevel) \
428 ((verboselevel) <= ::logging::GetVlogLevel(__FILE__))
429
430// Helper macro which avoids evaluating the arguments to a stream if
chcunninghamf6a96082015-02-07 01:58:37431// the condition doesn't hold. Condition is evaluated once and only once.
akalin@chromium.org521b0c42010-10-01 23:02:36432#define LAZY_STREAM(stream, condition) \
433 !(condition) ? (void) 0 : ::logging::LogMessageVoidify() & (stream)
initial.commitd7cae122008-07-26 21:49:38434
435// We use the preprocessor's merging operator, "##", so that, e.g.,
436// LOG(INFO) becomes the token COMPACT_GOOGLE_LOG_INFO. There's some funny
437// subtle difference between ostream member streaming functions (e.g.,
438// ostream::operator<<(int) and ostream non-member streaming functions
439// (e.g., ::operator<<(ostream&, string&): it turns out that it's
440// impossible to stream something like a string directly to an unnamed
441// ostream. We employ a neat hack by calling the stream() member
442// function of LogMessage which seems to avoid the problem.
akalin@chromium.org521b0c42010-10-01 23:02:36443#define LOG_STREAM(severity) COMPACT_GOOGLE_LOG_ ## severity.stream()
initial.commitd7cae122008-07-26 21:49:38444
akalin@chromium.org521b0c42010-10-01 23:02:36445#define LOG(severity) LAZY_STREAM(LOG_STREAM(severity), LOG_IS_ON(severity))
446#define LOG_IF(severity, condition) \
447 LAZY_STREAM(LOG_STREAM(severity), LOG_IS_ON(severity) && (condition))
448
siggi@chromium.org162ac0f2010-11-04 15:50:49449// The VLOG macros log with negative verbosities.
450#define VLOG_STREAM(verbose_level) \
tsniatowski612550f2016-07-21 18:26:20451 ::logging::LogMessage(__FILE__, __LINE__, -verbose_level).stream()
siggi@chromium.org162ac0f2010-11-04 15:50:49452
453#define VLOG(verbose_level) \
454 LAZY_STREAM(VLOG_STREAM(verbose_level), VLOG_IS_ON(verbose_level))
455
456#define VLOG_IF(verbose_level, condition) \
457 LAZY_STREAM(VLOG_STREAM(verbose_level), \
458 VLOG_IS_ON(verbose_level) && (condition))
akalin@chromium.org99b7c57f2010-09-29 19:26:36459
sail@chromium.orgfb879b1a2011-03-06 18:16:31460#if defined (OS_WIN)
461#define VPLOG_STREAM(verbose_level) \
tsniatowski612550f2016-07-21 18:26:20462 ::logging::Win32ErrorLogMessage(__FILE__, __LINE__, -verbose_level, \
sail@chromium.orgfb879b1a2011-03-06 18:16:31463 ::logging::GetLastSystemErrorCode()).stream()
Fabrice de Gans-Riberi306871de2018-05-16 19:38:39464#elif defined(OS_POSIX) || defined(OS_FUCHSIA)
sail@chromium.orgfb879b1a2011-03-06 18:16:31465#define VPLOG_STREAM(verbose_level) \
tsniatowski612550f2016-07-21 18:26:20466 ::logging::ErrnoLogMessage(__FILE__, __LINE__, -verbose_level, \
sail@chromium.orgfb879b1a2011-03-06 18:16:31467 ::logging::GetLastSystemErrorCode()).stream()
468#endif
469
470#define VPLOG(verbose_level) \
471 LAZY_STREAM(VPLOG_STREAM(verbose_level), VLOG_IS_ON(verbose_level))
472
473#define VPLOG_IF(verbose_level, condition) \
474 LAZY_STREAM(VPLOG_STREAM(verbose_level), \
475 VLOG_IS_ON(verbose_level) && (condition))
476
akalin@chromium.org99b7c57f2010-09-29 19:26:36477// TODO(akalin): Add more VLOG variants, e.g. VPLOG.
initial.commitd7cae122008-07-26 21:49:38478
kmarshallfe2f09f82017-04-20 21:05:26479#define LOG_ASSERT(condition) \
480 LOG_IF(FATAL, !(ANALYZER_ASSUME_TRUE(condition))) \
481 << "Assert failed: " #condition ". "
initial.commitd7cae122008-07-26 21:49:38482
tschmelcher@chromium.orgd8617a62009-10-09 23:52:20483#if defined(OS_WIN)
vitalybuka@chromium.orgc914d8a2014-04-23 01:11:01484#define PLOG_STREAM(severity) \
tschmelcher@chromium.orgd8617a62009-10-09 23:52:20485 COMPACT_GOOGLE_LOG_EX_ ## severity(Win32ErrorLogMessage, \
486 ::logging::GetLastSystemErrorCode()).stream()
Fabrice de Gans-Riberi306871de2018-05-16 19:38:39487#elif defined(OS_POSIX) || defined(OS_FUCHSIA)
vitalybuka@chromium.orgc914d8a2014-04-23 01:11:01488#define PLOG_STREAM(severity) \
tschmelcher@chromium.orgd8617a62009-10-09 23:52:20489 COMPACT_GOOGLE_LOG_EX_ ## severity(ErrnoLogMessage, \
490 ::logging::GetLastSystemErrorCode()).stream()
tschmelcher@chromium.orgd8617a62009-10-09 23:52:20491#endif
492
akalin@chromium.org521b0c42010-10-01 23:02:36493#define PLOG(severity) \
494 LAZY_STREAM(PLOG_STREAM(severity), LOG_IS_ON(severity))
495
tschmelcher@chromium.orgd8617a62009-10-09 23:52:20496#define PLOG_IF(severity, condition) \
akalin@chromium.org521b0c42010-10-01 23:02:36497 LAZY_STREAM(PLOG_STREAM(severity), LOG_IS_ON(severity) && (condition))
tschmelcher@chromium.orgd8617a62009-10-09 23:52:20498
scottmg3c957a52016-12-10 20:57:59499BASE_EXPORT extern std::ostream* g_swallow_stream;
500
501// Note that g_swallow_stream is used instead of an arbitrary LOG() stream to
502// avoid the creation of an object with a non-trivial destructor (LogMessage).
503// On MSVC x86 (checked on 2015 Update 3), this causes a few additional
504// pointless instructions to be emitted even at full optimization level, even
505// though the : arm of the ternary operator is clearly never executed. Using a
506// simpler object to be &'d with Voidify() avoids these extra instructions.
507// Using a simpler POD object with a templated operator<< also works to avoid
508// these instructions. However, this causes warnings on statically defined
509// implementations of operator<<(std::ostream, ...) in some .cc files, because
510// they become defined-but-unreferenced functions. A reinterpret_cast of 0 to an
511// ostream* also is not suitable, because some compilers warn of undefined
512// behavior.
513#define EAT_STREAM_PARAMETERS \
514 true ? (void)0 \
515 : ::logging::LogMessageVoidify() & (*::logging::g_swallow_stream)
akalin@chromium.orgddb9b332011-12-02 07:31:09516
erikwright6ad937b2015-07-22 20:05:52517// Captures the result of a CHECK_EQ (for example) and facilitates testing as a
518// boolean.
519class CheckOpResult {
520 public:
wezf01a9b72016-03-19 01:18:07521 // |message| must be non-null if and only if the check failed.
erikwright6ad937b2015-07-22 20:05:52522 CheckOpResult(std::string* message) : message_(message) {}
523 // Returns true if the check succeeded.
524 operator bool() const { return !message_; }
525 // Returns the message.
526 std::string* message() { return message_; }
527
528 private:
529 std::string* message_;
530};
531
initial.commitd7cae122008-07-26 21:49:38532// CHECK dies with a fatal error if condition is not true. It is *not*
533// controlled by NDEBUG, so the check will be executed regardless of
534// compilation mode.
akalin@chromium.org521b0c42010-10-01 23:02:36535//
536// We make sure CHECK et al. always evaluates their arguments, as
537// doing CHECK(FunctionWithSideEffect()) is a common idiom.
akalin@chromium.orgddb9b332011-12-02 07:31:09538
danakjb9d59312016-05-04 20:06:31539#if defined(OFFICIAL_BUILD) && defined(NDEBUG)
akalin@chromium.orgddb9b332011-12-02 07:31:09540
Chris Palmer61343b02016-11-29 20:44:10541// Make all CHECK functions discard their log strings to reduce code bloat, and
542// improve performance, for official release builds.
543//
primianoba910a62016-07-07 22:14:48544// This is not calling BreakDebugger since this is called frequently, and
545// calling an out-of-line function instead of a noreturn inline macro prevents
546// compiler optimizations.
Chris Palmer61343b02016-11-29 20:44:10547#define CHECK(condition) \
danakjcb7c5292016-12-20 19:05:35548 UNLIKELY(!(condition)) ? IMMEDIATE_CRASH() : EAT_STREAM_PARAMETERS
akalin@chromium.orgddb9b332011-12-02 07:31:09549
Robert Sesekd2f495f2017-07-25 22:03:14550// PCHECK includes the system error code, which is useful for determining
551// why the condition failed. In official builds, preserve only the error code
552// message so that it is available in crash reports. The stringified
553// condition and any additional stream parameters are dropped.
554#define PCHECK(condition) \
555 LAZY_STREAM(PLOG_STREAM(FATAL), UNLIKELY(!(condition))); \
556 EAT_STREAM_PARAMETERS
akalin@chromium.orgddb9b332011-12-02 07:31:09557
558#define CHECK_OP(name, op, val1, val2) CHECK((val1) op (val2))
559
danakjb9d59312016-05-04 20:06:31560#else // !(OFFICIAL_BUILD && NDEBUG)
akalin@chromium.orgddb9b332011-12-02 07:31:09561
tnagel4a045d3f2015-07-12 14:19:28562// Do as much work as possible out of line to reduce inline code size.
tsniatowski612550f2016-07-21 18:26:20563#define CHECK(condition) \
564 LAZY_STREAM(::logging::LogMessage(__FILE__, __LINE__, #condition).stream(), \
kmarshallfe2f09f82017-04-20 21:05:26565 !ANALYZER_ASSUME_TRUE(condition))
initial.commitd7cae122008-07-26 21:49:38566
kmarshallfe2f09f82017-04-20 21:05:26567#define PCHECK(condition) \
568 LAZY_STREAM(PLOG_STREAM(FATAL), !ANALYZER_ASSUME_TRUE(condition)) \
kmarshalle23eed02017-02-11 02:13:23569 << "Check failed: " #condition ". "
brucedawson9d160252014-10-23 20:14:14570
akalin@chromium.orgddb9b332011-12-02 07:31:09571// Helper macro for binary operators.
572// Don't use this macro directly in your code, use CHECK_EQ et al below.
erikwright6ad937b2015-07-22 20:05:52573// The 'switch' is used to prevent the 'else' from being ambiguous when the
574// macro is used in an 'if' clause such as:
575// if (a == 1)
576// CHECK_EQ(2, a);
577#define CHECK_OP(name, op, val1, val2) \
578 switch (0) case 0: default: \
tsniatowski612550f2016-07-21 18:26:20579 if (::logging::CheckOpResult true_if_passed = \
580 ::logging::Check##name##Impl((val1), (val2), \
581 #val1 " " #op " " #val2)) \
erikwright6ad937b2015-07-22 20:05:52582 ; \
583 else \
tsniatowski612550f2016-07-21 18:26:20584 ::logging::LogMessage(__FILE__, __LINE__, true_if_passed.message()).stream()
akalin@chromium.orgddb9b332011-12-02 07:31:09585
danakjb9d59312016-05-04 20:06:31586#endif // !(OFFICIAL_BUILD && NDEBUG)
akalin@chromium.orgddb9b332011-12-02 07:31:09587
brucedawson93a60b8c2016-04-28 20:46:16588// This formats a value for a failing CHECK_XX statement. Ordinarily,
589// it uses the definition for operator<<, with a few special cases below.
590template <typename T>
jbroman6bcfec422016-05-26 00:28:46591inline typename std::enable_if<
raphael.kubo.da.costa81f21202016-11-28 18:36:36592 base::internal::SupportsOstreamOperator<const T&>::value &&
593 !std::is_function<typename std::remove_pointer<T>::type>::value,
jbroman6bcfec422016-05-26 00:28:46594 void>::type
595MakeCheckOpValueString(std::ostream* os, const T& v) {
brucedawson93a60b8c2016-04-28 20:46:16596 (*os) << v;
597}
598
Collin Baker89e9e072019-06-10 22:39:05599// Overload for types that no operator<< but do have .ToString() defined.
600template <typename T>
601inline typename std::enable_if<
602 !base::internal::SupportsOstreamOperator<const T&>::value &&
603 base::internal::SupportsToString<const T&>::value,
604 void>::type
605MakeCheckOpValueString(std::ostream* os, const T& v) {
606 (*os) << v.ToString();
607}
608
raphael.kubo.da.costa81f21202016-11-28 18:36:36609// Provide an overload for functions and function pointers. Function pointers
610// don't implicitly convert to void* but do implicitly convert to bool, so
611// without this function pointers are always printed as 1 or 0. (MSVC isn't
612// standards-conforming here and converts function pointers to regular
613// pointers, so this is a no-op for MSVC.)
614template <typename T>
615inline typename std::enable_if<
616 std::is_function<typename std::remove_pointer<T>::type>::value,
617 void>::type
618MakeCheckOpValueString(std::ostream* os, const T& v) {
619 (*os) << reinterpret_cast<const void*>(v);
620}
621
jbroman6bcfec422016-05-26 00:28:46622// We need overloads for enums that don't support operator<<.
623// (i.e. scoped enums where no operator<< overload was declared).
624template <typename T>
625inline typename std::enable_if<
626 !base::internal::SupportsOstreamOperator<const T&>::value &&
627 std::is_enum<T>::value,
628 void>::type
629MakeCheckOpValueString(std::ostream* os, const T& v) {
danakj6d0446e52017-04-05 16:22:29630 (*os) << static_cast<typename std::underlying_type<T>::type>(v);
jbroman6bcfec422016-05-26 00:28:46631}
632
633// We need an explicit overload for std::nullptr_t.
634BASE_EXPORT void MakeCheckOpValueString(std::ostream* os, std::nullptr_t p);
brucedawson93a60b8c2016-04-28 20:46:16635
initial.commitd7cae122008-07-26 21:49:38636// Build the error message string. This is separate from the "Impl"
637// function template because it is not performance critical and so can
akalin@chromium.org9c7132e2011-02-08 07:39:08638// be out of line, while the "Impl" code should be inline. Caller
639// takes ownership of the returned string.
initial.commitd7cae122008-07-26 21:49:38640template<class t1, class t2>
641std::string* MakeCheckOpString(const t1& v1, const t2& v2, const char* names) {
642 std::ostringstream ss;
brucedawson93a60b8c2016-04-28 20:46:16643 ss << names << " (";
644 MakeCheckOpValueString(&ss, v1);
645 ss << " vs. ";
646 MakeCheckOpValueString(&ss, v2);
647 ss << ")";
initial.commitd7cae122008-07-26 21:49:38648 std::string* msg = new std::string(ss.str());
649 return msg;
650}
651
erg@google.com6d445d32010-09-30 19:10:03652// Commonly used instantiations of MakeCheckOpString<>. Explicitly instantiated
653// in logging.cc.
erg@chromium.orgdc72da32011-10-24 20:20:30654extern template BASE_EXPORT std::string* MakeCheckOpString<int, int>(
erg@google.com6d445d32010-09-30 19:10:03655 const int&, const int&, const char* names);
erg@chromium.orgdc72da32011-10-24 20:20:30656extern template BASE_EXPORT
657std::string* MakeCheckOpString<unsigned long, unsigned long>(
erg@google.com6d445d32010-09-30 19:10:03658 const unsigned long&, const unsigned long&, const char* names);
erg@chromium.orgdc72da32011-10-24 20:20:30659extern template BASE_EXPORT
660std::string* MakeCheckOpString<unsigned long, unsigned int>(
erg@google.com6d445d32010-09-30 19:10:03661 const unsigned long&, const unsigned int&, const char* names);
erg@chromium.orgdc72da32011-10-24 20:20:30662extern template BASE_EXPORT
663std::string* MakeCheckOpString<unsigned int, unsigned long>(
erg@google.com6d445d32010-09-30 19:10:03664 const unsigned int&, const unsigned long&, const char* names);
erg@chromium.orgdc72da32011-10-24 20:20:30665extern template BASE_EXPORT
666std::string* MakeCheckOpString<std::string, std::string>(
erg@google.com6d445d32010-09-30 19:10:03667 const std::string&, const std::string&, const char* name);
initial.commitd7cae122008-07-26 21:49:38668
akalin@chromium.org71512602010-11-01 22:19:56669// Helper functions for CHECK_OP macro.
670// The (int, int) specialization works around the issue that the compiler
671// will not instantiate the template version of the function on values of
672// unnamed enum type - see comment below.
kmarshallfe2f09f82017-04-20 21:05:26673//
674// The checked condition is wrapped with ANALYZER_ASSUME_TRUE, which under
675// static analysis builds, blocks analysis of the current path if the
676// condition is false.
kmarshall9db26fb2017-02-15 01:05:33677#define DEFINE_CHECK_OP_IMPL(name, op) \
678 template <class t1, class t2> \
679 inline std::string* Check##name##Impl(const t1& v1, const t2& v2, \
680 const char* names) { \
kmarshallfe2f09f82017-04-20 21:05:26681 if (ANALYZER_ASSUME_TRUE(v1 op v2)) \
kmarshall9db26fb2017-02-15 01:05:33682 return NULL; \
683 else \
684 return ::logging::MakeCheckOpString(v1, v2, names); \
685 } \
akalin@chromium.org71512602010-11-01 22:19:56686 inline std::string* Check##name##Impl(int v1, int v2, const char* names) { \
kmarshallfe2f09f82017-04-20 21:05:26687 if (ANALYZER_ASSUME_TRUE(v1 op v2)) \
kmarshall9db26fb2017-02-15 01:05:33688 return NULL; \
689 else \
690 return ::logging::MakeCheckOpString(v1, v2, names); \
akalin@chromium.org71512602010-11-01 22:19:56691 }
692DEFINE_CHECK_OP_IMPL(EQ, ==)
693DEFINE_CHECK_OP_IMPL(NE, !=)
694DEFINE_CHECK_OP_IMPL(LE, <=)
695DEFINE_CHECK_OP_IMPL(LT, < )
696DEFINE_CHECK_OP_IMPL(GE, >=)
697DEFINE_CHECK_OP_IMPL(GT, > )
698#undef DEFINE_CHECK_OP_IMPL
willchan@chromium.orge150c0382010-03-02 00:41:12699
700#define CHECK_EQ(val1, val2) CHECK_OP(EQ, ==, val1, val2)
701#define CHECK_NE(val1, val2) CHECK_OP(NE, !=, val1, val2)
702#define CHECK_LE(val1, val2) CHECK_OP(LE, <=, val1, val2)
703#define CHECK_LT(val1, val2) CHECK_OP(LT, < , val1, val2)
704#define CHECK_GE(val1, val2) CHECK_OP(GE, >=, val1, val2)
705#define CHECK_GT(val1, val2) CHECK_OP(GT, > , val1, val2)
706
jam121900aa2016-04-19 00:07:34707#if defined(NDEBUG) && !defined(DCHECK_ALWAYS_ON)
danakje649f572015-01-08 23:35:58708#define DCHECK_IS_ON() 0
wangxianzhu@chromium.org1a1505512014-03-10 18:23:38709#else
danakje649f572015-01-08 23:35:58710#define DCHECK_IS_ON() 1
mark@chromium.orge3cca332009-08-20 01:20:29711#endif
712
akalin@chromium.orgd15e56c2010-09-30 21:12:33713// Definitions for DLOG et al.
714
gab190f7542016-08-01 20:03:41715#if DCHECK_IS_ON()
akalin@chromium.orgd926c202010-10-01 02:58:24716
akalin@chromium.org5e987802010-11-01 19:49:22717#define DLOG_IS_ON(severity) LOG_IS_ON(severity)
akalin@chromium.orgd926c202010-10-01 02:58:24718#define DLOG_IF(severity, condition) LOG_IF(severity, condition)
719#define DLOG_ASSERT(condition) LOG_ASSERT(condition)
akalin@chromium.orgd926c202010-10-01 02:58:24720#define DPLOG_IF(severity, condition) PLOG_IF(severity, condition)
akalin@chromium.org521b0c42010-10-01 23:02:36721#define DVLOG_IF(verboselevel, condition) VLOG_IF(verboselevel, condition)
sail@chromium.orgfb879b1a2011-03-06 18:16:31722#define DVPLOG_IF(verboselevel, condition) VPLOG_IF(verboselevel, condition)
akalin@chromium.orgd926c202010-10-01 02:58:24723
gab190f7542016-08-01 20:03:41724#else // DCHECK_IS_ON()
akalin@chromium.orgd926c202010-10-01 02:58:24725
gab190f7542016-08-01 20:03:41726// If !DCHECK_IS_ON(), we want to avoid emitting any references to |condition|
727// (which may reference a variable defined only if DCHECK_IS_ON()).
728// Contrast this with DCHECK et al., which has different behavior.
akalin@chromium.orgd926c202010-10-01 02:58:24729
akalin@chromium.org5e987802010-11-01 19:49:22730#define DLOG_IS_ON(severity) false
akalin@chromium.orgddb9b332011-12-02 07:31:09731#define DLOG_IF(severity, condition) EAT_STREAM_PARAMETERS
732#define DLOG_ASSERT(condition) EAT_STREAM_PARAMETERS
733#define DPLOG_IF(severity, condition) EAT_STREAM_PARAMETERS
734#define DVLOG_IF(verboselevel, condition) EAT_STREAM_PARAMETERS
735#define DVPLOG_IF(verboselevel, condition) EAT_STREAM_PARAMETERS
akalin@chromium.orgd926c202010-10-01 02:58:24736
gab190f7542016-08-01 20:03:41737#endif // DCHECK_IS_ON()
akalin@chromium.orgd926c202010-10-01 02:58:24738
akalin@chromium.org521b0c42010-10-01 23:02:36739#define DLOG(severity) \
740 LAZY_STREAM(LOG_STREAM(severity), DLOG_IS_ON(severity))
741
akalin@chromium.org521b0c42010-10-01 23:02:36742#define DPLOG(severity) \
743 LAZY_STREAM(PLOG_STREAM(severity), DLOG_IS_ON(severity))
744
Ken MacKay70e8867002019-01-16 00:22:15745#define DVLOG(verboselevel) DVLOG_IF(verboselevel, true)
akalin@chromium.org521b0c42010-10-01 23:02:36746
Ken MacKay70e8867002019-01-16 00:22:15747#define DVPLOG(verboselevel) DVPLOG_IF(verboselevel, true)
sail@chromium.orgfb879b1a2011-03-06 18:16:31748
akalin@chromium.org521b0c42010-10-01 23:02:36749// Definitions for DCHECK et al.
akalin@chromium.orgd926c202010-10-01 02:58:24750
danakje649f572015-01-08 23:35:58751#if DCHECK_IS_ON()
mark@chromium.orge3cca332009-08-20 01:20:29752
Tomas Popelaafffa972018-11-13 20:42:05753#if defined(DCHECK_IS_CONFIGURABLE)
Wez289477f2017-08-24 20:51:30754BASE_EXPORT extern LogSeverity LOG_DCHECK;
755#else
akalin@chromium.org521b0c42010-10-01 23:02:36756const LogSeverity LOG_DCHECK = LOG_FATAL;
Tomas Popelaafffa972018-11-13 20:42:05757#endif // defined(DCHECK_IS_CONFIGURABLE)
akalin@chromium.org521b0c42010-10-01 23:02:36758
danakje649f572015-01-08 23:35:58759#else // DCHECK_IS_ON()
akalin@chromium.org521b0c42010-10-01 23:02:36760
Sigurdur Asgeirsson7013e5f2017-09-29 17:42:58761// There may be users of LOG_DCHECK that are enabled independently
762// of DCHECK_IS_ON(), so default to FATAL logging for those.
763const LogSeverity LOG_DCHECK = LOG_FATAL;
akalin@chromium.org521b0c42010-10-01 23:02:36764
danakje649f572015-01-08 23:35:58765#endif // DCHECK_IS_ON()
akalin@chromium.org521b0c42010-10-01 23:02:36766
akalin@chromium.orgdeba0ff2010-11-03 05:30:14767// DCHECK et al. make sure to reference |condition| regardless of
akalin@chromium.org521b0c42010-10-01 23:02:36768// whether DCHECKs are enabled; this is so that we don't get unused
769// variable warnings if the only use of a variable is in a DCHECK.
770// This behavior is different from DLOG_IF et al.
dchengfc670f472017-01-25 17:48:43771//
772// Note that the definition of the DCHECK macros depends on whether or not
773// DCHECK_IS_ON() is true. When DCHECK_IS_ON() is false, the macros use
774// EAT_STREAM_PARAMETERS to avoid expressions that would create temporaries.
akalin@chromium.org521b0c42010-10-01 23:02:36775
dchengfc670f472017-01-25 17:48:43776#if DCHECK_IS_ON()
777
kmarshallfe2f09f82017-04-20 21:05:26778#define DCHECK(condition) \
779 LAZY_STREAM(LOG_STREAM(DCHECK), !ANALYZER_ASSUME_TRUE(condition)) \
dchengfc670f472017-01-25 17:48:43780 << "Check failed: " #condition ". "
kmarshallfe2f09f82017-04-20 21:05:26781#define DPCHECK(condition) \
782 LAZY_STREAM(PLOG_STREAM(DCHECK), !ANALYZER_ASSUME_TRUE(condition)) \
danakje649f572015-01-08 23:35:58783 << "Check failed: " #condition ". "
akalin@chromium.org521b0c42010-10-01 23:02:36784
dchengfc670f472017-01-25 17:48:43785#else // DCHECK_IS_ON()
786
kmarshall08c892f72017-02-28 03:46:18787#define DCHECK(condition) EAT_STREAM_PARAMETERS << !(condition)
788#define DPCHECK(condition) EAT_STREAM_PARAMETERS << !(condition)
dchengfc670f472017-01-25 17:48:43789
790#endif // DCHECK_IS_ON()
akalin@chromium.orgd926c202010-10-01 02:58:24791
792// Helper macro for binary operators.
793// Don't use this macro directly in your code, use DCHECK_EQ et al below.
erikwright6ad937b2015-07-22 20:05:52794// The 'switch' is used to prevent the 'else' from being ambiguous when the
795// macro is used in an 'if' clause such as:
796// if (a == 1)
797// DCHECK_EQ(2, a);
dchengfc670f472017-01-25 17:48:43798#if DCHECK_IS_ON()
799
tsniatowski612550f2016-07-21 18:26:20800#define DCHECK_OP(name, op, val1, val2) \
801 switch (0) case 0: default: \
802 if (::logging::CheckOpResult true_if_passed = \
tsniatowski612550f2016-07-21 18:26:20803 ::logging::Check##name##Impl((val1), (val2), \
Wez6a592ee2018-05-25 20:29:07804 #val1 " " #op " " #val2)) \
tsniatowski612550f2016-07-21 18:26:20805 ; \
806 else \
807 ::logging::LogMessage(__FILE__, __LINE__, ::logging::LOG_DCHECK, \
808 true_if_passed.message()).stream()
initial.commitd7cae122008-07-26 21:49:38809
dchengfc670f472017-01-25 17:48:43810#else // DCHECK_IS_ON()
811
812// When DCHECKs aren't enabled, DCHECK_OP still needs to reference operator<<
813// overloads for |val1| and |val2| to avoid potential compiler warnings about
814// unused functions. For the same reason, it also compares |val1| and |val2|
815// using |op|.
816//
817// Note that the contract of DCHECK_EQ, etc is that arguments are only evaluated
818// once. Even though |val1| and |val2| appear twice in this version of the macro
819// expansion, this is OK, since the expression is never actually evaluated.
820#define DCHECK_OP(name, op, val1, val2) \
821 EAT_STREAM_PARAMETERS << (::logging::MakeCheckOpValueString( \
822 ::logging::g_swallow_stream, val1), \
823 ::logging::MakeCheckOpValueString( \
824 ::logging::g_swallow_stream, val2), \
kmarshall08c892f72017-02-28 03:46:18825 (val1)op(val2))
dchengfc670f472017-01-25 17:48:43826
827#endif // DCHECK_IS_ON()
828
akalin@chromium.orgdeba0ff2010-11-03 05:30:14829// Equality/Inequality checks - compare two values, and log a
830// LOG_DCHECK message including the two values when the result is not
831// as expected. The values must have operator<<(ostream, ...)
832// defined.
initial.commitd7cae122008-07-26 21:49:38833//
834// You may append to the error message like so:
pwnall7ae42b462016-09-22 02:26:12835// DCHECK_NE(1, 2) << "The world must be ending!";
initial.commitd7cae122008-07-26 21:49:38836//
837// We are very careful to ensure that each argument is evaluated exactly
838// once, and that anything which is legal to pass as a function argument is
839// legal here. In particular, the arguments may be temporary expressions
840// which will end up being destroyed at the end of the apparent statement,
841// for example:
842// DCHECK_EQ(string("abc")[1], 'b');
843//
brucedawson93a60b8c2016-04-28 20:46:16844// WARNING: These don't compile correctly if one of the arguments is a pointer
845// and the other is NULL. In new code, prefer nullptr instead. To
846// work around this for C++98, simply static_cast NULL to the type of the
847// desired pointer.
initial.commitd7cae122008-07-26 21:49:38848
849#define DCHECK_EQ(val1, val2) DCHECK_OP(EQ, ==, val1, val2)
850#define DCHECK_NE(val1, val2) DCHECK_OP(NE, !=, val1, val2)
851#define DCHECK_LE(val1, val2) DCHECK_OP(LE, <=, val1, val2)
852#define DCHECK_LT(val1, val2) DCHECK_OP(LT, < , val1, val2)
853#define DCHECK_GE(val1, val2) DCHECK_OP(GE, >=, val1, val2)
854#define DCHECK_GT(val1, val2) DCHECK_OP(GT, > , val1, val2)
855
Xiaohan Wangee536b212019-05-07 16:16:07856#if BUILDFLAG(ENABLE_LOG_ERROR_NOT_REACHED)
tnagelff3f34a2015-05-24 12:59:14857// Implement logging of NOTREACHED() as a dedicated function to get function
858// call overhead down to a minimum.
859void LogErrorNotReached(const char* file, int line);
860#define NOTREACHED() \
861 true ? ::logging::LogErrorNotReached(__FILE__, __LINE__) \
862 : EAT_STREAM_PARAMETERS
zork@chromium.org7c67fbe2013-09-26 07:55:21863#else
initial.commitd7cae122008-07-26 21:49:38864#define NOTREACHED() DCHECK(false)
zork@chromium.org7c67fbe2013-09-26 07:55:21865#endif
initial.commitd7cae122008-07-26 21:49:38866
867// Redefine the standard assert to use our nice log files
868#undef assert
869#define assert(x) DLOG_ASSERT(x)
870
871// This class more or less represents a particular log message. You
872// create an instance of LogMessage and then stream stuff to it.
873// When you finish streaming to it, ~LogMessage is called and the
874// full message gets streamed to the appropriate destination.
875//
876// You shouldn't actually use LogMessage's constructor to log things,
877// though. You should use the LOG() macro (and variants thereof)
878// above.
darin@chromium.org0bea7252011-08-05 15:34:00879class BASE_EXPORT LogMessage {
initial.commitd7cae122008-07-26 21:49:38880 public:
viettrungluu@chromium.orgbf8ddf13a2014-06-18 15:02:22881 // Used for LOG(severity).
initial.commitd7cae122008-07-26 21:49:38882 LogMessage(const char* file, int line, LogSeverity severity);
883
tnagel4a045d3f2015-07-12 14:19:28884 // Used for CHECK(). Implied severity = LOG_FATAL.
885 LogMessage(const char* file, int line, const char* condition);
886
viettrungluu@chromium.orgbf8ddf13a2014-06-18 15:02:22887 // Used for CHECK_EQ(), etc. Takes ownership of the given string.
888 // Implied severity = LOG_FATAL.
akalin@chromium.org9c7132e2011-02-08 07:39:08889 LogMessage(const char* file, int line, std::string* result);
initial.commitd7cae122008-07-26 21:49:38890
viettrungluu@chromium.orgbf8ddf13a2014-06-18 15:02:22891 // Used for DCHECK_EQ(), etc. Takes ownership of the given string.
huanr@chromium.orgfb62a532009-02-12 01:19:05892 LogMessage(const char* file, int line, LogSeverity severity,
akalin@chromium.org9c7132e2011-02-08 07:39:08893 std::string* result);
huanr@chromium.orgfb62a532009-02-12 01:19:05894
initial.commitd7cae122008-07-26 21:49:38895 ~LogMessage();
896
897 std::ostream& stream() { return stream_; }
898
pastarmovj89f7ee12016-09-20 14:58:13899 LogSeverity severity() { return severity_; }
900 std::string str() { return stream_.str(); }
901
initial.commitd7cae122008-07-26 21:49:38902 private:
903 void Init(const char* file, int line);
904
905 LogSeverity severity_;
906 std::ostringstream stream_;
maruel@google.comc88873922008-07-30 13:02:03907 size_t message_start_; // Offset of the start of the message (past prefix
908 // info).
siggi@chromium.org162ac0f2010-11-04 15:50:49909 // The file and line information passed in to the constructor.
910 const char* file_;
911 const int line_;
912
tommi@google.com3f85caa2009-04-14 16:52:11913 // This is useful since the LogMessage class uses a lot of Win32 calls
914 // that will lose the value of GLE and the code that called the log function
915 // will have lost the thread error value when the log call returns.
Etienne Pierre-Dorayd120ebf2018-09-14 23:38:21916 base::internal::ScopedClearLastError last_error_;
initial.commitd7cae122008-07-26 21:49:38917
brettw@google.com39be4242008-08-07 18:31:40918 DISALLOW_COPY_AND_ASSIGN(LogMessage);
initial.commitd7cae122008-07-26 21:49:38919};
920
initial.commitd7cae122008-07-26 21:49:38921// This class is used to explicitly ignore values in the conditional
922// logging macros. This avoids compiler warnings like "value computed
923// is not used" and "statement has no effect".
rvargas@google.com23bb71f2011-04-21 22:22:10924class LogMessageVoidify {
initial.commitd7cae122008-07-26 21:49:38925 public:
Chris Watkins091d6292017-12-13 04:25:58926 LogMessageVoidify() = default;
initial.commitd7cae122008-07-26 21:49:38927 // This has to be an operator with a precedence lower than << but
928 // higher than ?:
929 void operator&(std::ostream&) { }
930};
931
tschmelcher@chromium.orgd8617a62009-10-09 23:52:20932#if defined(OS_WIN)
933typedef unsigned long SystemErrorCode;
Fabrice de Gans-Riberi306871de2018-05-16 19:38:39934#elif defined(OS_POSIX) || defined(OS_FUCHSIA)
tschmelcher@chromium.orgd8617a62009-10-09 23:52:20935typedef int SystemErrorCode;
936#endif
937
938// Alias for ::GetLastError() on Windows and errno on POSIX. Avoids having to
939// pull in windows.h just for GetLastError() and DWORD.
darin@chromium.org0bea7252011-08-05 15:34:00940BASE_EXPORT SystemErrorCode GetLastSystemErrorCode();
vitalybuka@chromium.orgc914d8a2014-04-23 01:11:01941BASE_EXPORT std::string SystemErrorCodeToString(SystemErrorCode error_code);
tschmelcher@chromium.orgd8617a62009-10-09 23:52:20942
943#if defined(OS_WIN)
944// Appends a formatted system message of the GetLastError() type.
darin@chromium.org0bea7252011-08-05 15:34:00945class BASE_EXPORT Win32ErrorLogMessage {
tschmelcher@chromium.orgd8617a62009-10-09 23:52:20946 public:
947 Win32ErrorLogMessage(const char* file,
948 int line,
949 LogSeverity severity,
tschmelcher@chromium.orgd8617a62009-10-09 23:52:20950 SystemErrorCode err);
951
tschmelcher@chromium.orgd8617a62009-10-09 23:52:20952 // Appends the error message before destructing the encapsulated class.
953 ~Win32ErrorLogMessage();
954
erg@google.coma502bbe72011-01-07 18:06:45955 std::ostream& stream() { return log_message_.stream(); }
956
tschmelcher@chromium.orgd8617a62009-10-09 23:52:20957 private:
958 SystemErrorCode err_;
tschmelcher@chromium.orgd8617a62009-10-09 23:52:20959 LogMessage log_message_;
960
961 DISALLOW_COPY_AND_ASSIGN(Win32ErrorLogMessage);
962};
Fabrice de Gans-Riberi306871de2018-05-16 19:38:39963#elif defined(OS_POSIX) || defined(OS_FUCHSIA)
tschmelcher@chromium.orgd8617a62009-10-09 23:52:20964// Appends a formatted system message of the errno type
darin@chromium.org0bea7252011-08-05 15:34:00965class BASE_EXPORT ErrnoLogMessage {
tschmelcher@chromium.orgd8617a62009-10-09 23:52:20966 public:
967 ErrnoLogMessage(const char* file,
968 int line,
969 LogSeverity severity,
970 SystemErrorCode err);
971
tschmelcher@chromium.orgd8617a62009-10-09 23:52:20972 // Appends the error message before destructing the encapsulated class.
973 ~ErrnoLogMessage();
974
erg@google.coma502bbe72011-01-07 18:06:45975 std::ostream& stream() { return log_message_.stream(); }
976
tschmelcher@chromium.orgd8617a62009-10-09 23:52:20977 private:
978 SystemErrorCode err_;
979 LogMessage log_message_;
980
981 DISALLOW_COPY_AND_ASSIGN(ErrnoLogMessage);
982};
983#endif // OS_WIN
984
initial.commitd7cae122008-07-26 21:49:38985// Closes the log file explicitly if open.
986// NOTE: Since the log file is opened as necessary by the action of logging
987// statements, there's no guarantee that it will stay closed
988// after this call.
darin@chromium.org0bea7252011-08-05 15:34:00989BASE_EXPORT void CloseLogFile();
initial.commitd7cae122008-07-26 21:49:38990
willchan@chromium.orge36ddc82009-12-08 04:22:50991// Async signal safe logging mechanism.
darin@chromium.org0bea7252011-08-05 15:34:00992BASE_EXPORT void RawLog(int level, const char* message);
willchan@chromium.orge36ddc82009-12-08 04:22:50993
tsniatowski612550f2016-07-21 18:26:20994#define RAW_LOG(level, message) \
995 ::logging::RawLog(::logging::LOG_##level, message)
willchan@chromium.orge36ddc82009-12-08 04:22:50996
tsniatowski612550f2016-07-21 18:26:20997#define RAW_CHECK(condition) \
998 do { \
kmarshall08c892f72017-02-28 03:46:18999 if (!(condition)) \
tsniatowski612550f2016-07-21 18:26:201000 ::logging::RawLog(::logging::LOG_FATAL, \
1001 "Check failed: " #condition "\n"); \
willchan@chromium.orge36ddc82009-12-08 04:22:501002 } while (0)
1003
ananta@chromium.orgf01b88a2013-02-27 22:04:001004#if defined(OS_WIN)
ananta61762fb2015-09-18 01:00:091005// Returns true if logging to file is enabled.
1006BASE_EXPORT bool IsLoggingToFileEnabled();
1007
ananta@chromium.orgf01b88a2013-02-27 22:04:001008// Returns the default log file path.
jdoerrie5c4dc4e2019-02-01 18:02:331009BASE_EXPORT base::string16 GetLogFileFullPath();
ananta@chromium.orgf01b88a2013-02-27 22:04:001010#endif
1011
brettw@google.com39be4242008-08-07 18:31:401012} // namespace logging
initial.commitd7cae122008-07-26 21:49:381013
jyasskin@chromium.org81411c62014-07-08 23:03:061014// Note that "The behavior of a C++ program is undefined if it adds declarations
1015// or definitions to namespace std or to a namespace within namespace std unless
1016// otherwise specified." --C++11[namespace.std]
1017//
1018// We've checked that this particular definition has the intended behavior on
1019// our implementations, but it's prone to breaking in the future, and please
1020// don't imitate this in your own definitions without checking with some
1021// standard library experts.
1022namespace std {
thakis@chromium.org46ce5b562010-06-16 18:39:531023// These functions are provided as a convenience for logging, which is where we
1024// use streams (it is against Google style to use streams in other places). It
1025// is designed to allow you to emit non-ASCII Unicode strings to the log file,
1026// which is normally ASCII. It is relatively slow, so try not to use it for
1027// common cases. Non-ASCII characters will be converted to UTF-8 by these
1028// operators.
darin@chromium.org0bea7252011-08-05 15:34:001029BASE_EXPORT std::ostream& operator<<(std::ostream& out, const wchar_t* wstr);
thakis@chromium.org46ce5b562010-06-16 18:39:531030inline std::ostream& operator<<(std::ostream& out, const std::wstring& wstr) {
1031 return out << wstr.c_str();
1032}
jyasskin@chromium.org81411c62014-07-08 23:03:061033} // namespace std
thakis@chromium.org46ce5b562010-06-16 18:39:531034
Daniel Bratellff541192017-11-02 14:22:281035// The NOTIMPLEMENTED() macro annotates codepaths which have not been
1036// implemented yet. If output spam is a serious concern,
1037// NOTIMPLEMENTED_LOG_ONCE can be used.
ericroman@google.com0dfc81b2008-08-25 03:44:401038
agl@chromium.orgf6cda752008-10-30 23:54:261039#if defined(COMPILER_GCC)
1040// On Linux, with GCC, we can use __PRETTY_FUNCTION__ to get the demangled name
1041// of the current function in the NOTIMPLEMENTED message.
1042#define NOTIMPLEMENTED_MSG "Not implemented reached in " << __PRETTY_FUNCTION__
1043#else
1044#define NOTIMPLEMENTED_MSG "NOT IMPLEMENTED"
1045#endif
1046
Daniel Cheng5b0b3012019-04-26 00:58:041047#define NOTIMPLEMENTED() DLOG(ERROR) << NOTIMPLEMENTED_MSG
1048#define NOTIMPLEMENTED_LOG_ONCE() \
1049 do { \
1050 static bool logged_once = false; \
1051 DLOG_IF(ERROR, !logged_once) << NOTIMPLEMENTED_MSG; \
1052 logged_once = true; \
1053 } while (0); \
Daniel Bratellff541192017-11-02 14:22:281054 EAT_STREAM_PARAMETERS
ericroman@google.com0dfc81b2008-08-25 03:44:401055
brettw@google.com39be4242008-08-07 18:31:401056#endif // BASE_LOGGING_H_