blob: 772c274e2f19691f10bbe1c066e13b36e7828a03 [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>
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
[email protected]0bea7252011-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"
[email protected]90509cb2011-03-25 18:46:3827#include "build/build_config.h"
initial.commitd7cae122008-07-26 21:49:3828
Robbie McElrath8bf49842019-08-20 22:22:5329#if defined(OS_CHROMEOS)
30#include <cstdio>
31#endif
32
initial.commitd7cae122008-07-26 21:49:3833//
34// Optional message capabilities
35// -----------------------------
36// Assertion failed messages and fatal errors are displayed in a dialog box
37// before the application exits. However, running this UI creates a message
38// loop, which causes application messages to be processed and potentially
39// dispatched to existing application windows. Since the application is in a
40// bad state when this assertion dialog is displayed, these messages may not
41// get processed and hang the dialog, or the application might go crazy.
42//
43// Therefore, it can be beneficial to display the error dialog in a separate
44// process from the main application. When the logging system needs to display
45// a fatal error dialog box, it will look for a program called
46// "DebugMessage.exe" in the same directory as the application executable. It
47// will run this application with the message as the command line, and will
48// not include the name of the application as is traditional for easier
49// parsing.
50//
51// The code for DebugMessage.exe is only one line. In WinMain, do:
52// MessageBox(NULL, GetCommandLineW(), L"Fatal Error", 0);
53//
54// If DebugMessage.exe is not found, the logging code will use a normal
55// MessageBox, potentially causing the problems discussed above.
56
initial.commitd7cae122008-07-26 21:49:3857// Instructions
58// ------------
59//
60// Make a bunch of macros for logging. The way to log things is to stream
61// things to LOG(<a particular severity level>). E.g.,
62//
63// LOG(INFO) << "Found " << num_cookies << " cookies";
64//
65// You can also do conditional logging:
66//
67// LOG_IF(INFO, num_cookies > 10) << "Got lots of cookies";
68//
initial.commitd7cae122008-07-26 21:49:3869// The CHECK(condition) macro is active in both debug and release builds and
70// effectively performs a LOG(FATAL) which terminates the process and
71// generates a crashdump unless a debugger is attached.
72//
73// There are also "debug mode" logging macros like the ones above:
74//
75// DLOG(INFO) << "Found cookies";
76//
77// DLOG_IF(INFO, num_cookies > 10) << "Got lots of cookies";
78//
79// All "debug mode" logging is compiled away to nothing for non-debug mode
80// compiles. LOG_IF and development flags also work well together
81// because the code can be compiled away sometimes.
82//
83// We also have
84//
85// LOG_ASSERT(assertion);
86// DLOG_ASSERT(assertion);
87//
88// which is syntactic sugar for {,D}LOG_IF(FATAL, assert fails) << assertion;
89//
[email protected]99b7c57f2010-09-29 19:26:3690// There are "verbose level" logging macros. They look like
91//
92// VLOG(1) << "I'm printed when you run the program with --v=1 or more";
93// VLOG(2) << "I'm printed when you run the program with --v=2 or more";
94//
95// These always log at the INFO log level (when they log at all).
96// The verbose logging can also be turned on module-by-module. For instance,
[email protected]b0d38d4c2010-10-29 00:39:4897// --vmodule=profile=2,icon_loader=1,browser_*=3,*/chromeos/*=4 --v=0
[email protected]99b7c57f2010-09-29 19:26:3698// will cause:
99// a. VLOG(2) and lower messages to be printed from profile.{h,cc}
100// b. VLOG(1) and lower messages to be printed from icon_loader.{h,cc}
101// c. VLOG(3) and lower messages to be printed from files prefixed with
102// "browser"
[email protected]e11de722010-11-01 20:50:55103// d. VLOG(4) and lower messages to be printed from files under a
[email protected]b0d38d4c2010-10-29 00:39:48104// "chromeos" directory.
[email protected]e11de722010-11-01 20:50:55105// e. VLOG(0) and lower messages to be printed from elsewhere
[email protected]99b7c57f2010-09-29 19:26:36106//
107// The wildcarding functionality shown by (c) supports both '*' (match
[email protected]b0d38d4c2010-10-29 00:39:48108// 0 or more characters) and '?' (match any single character)
109// wildcards. Any pattern containing a forward or backward slash will
110// be tested against the whole pathname and not just the module.
111// E.g., "*/foo/bar/*=2" would change the logging level for all code
112// in source files under a "foo/bar" directory.
[email protected]99b7c57f2010-09-29 19:26:36113//
114// There's also VLOG_IS_ON(n) "verbose level" condition macro. To be used as
115//
116// if (VLOG_IS_ON(2)) {
117// // do some logging preparation and logging
118// // that can't be accomplished with just VLOG(2) << ...;
119// }
120//
121// There is also a VLOG_IF "verbose level" condition macro for sample
122// cases, when some extra computation and preparation for logs is not
123// needed.
124//
125// VLOG_IF(1, (size > 1024))
126// << "I'm printed when size is more than 1024 and when you run the "
127// "program with --v=1 or more";
128//
initial.commitd7cae122008-07-26 21:49:38129// We also override the standard 'assert' to use 'DLOG_ASSERT'.
130//
[email protected]d8617a62009-10-09 23:52:20131// Lastly, there is:
132//
133// PLOG(ERROR) << "Couldn't do foo";
134// DPLOG(ERROR) << "Couldn't do foo";
135// PLOG_IF(ERROR, cond) << "Couldn't do foo";
136// DPLOG_IF(ERROR, cond) << "Couldn't do foo";
137// PCHECK(condition) << "Couldn't do foo";
138// DPCHECK(condition) << "Couldn't do foo";
139//
140// which append the last system error to the message in string form (taken from
141// GetLastError() on Windows and errno on POSIX).
142//
initial.commitd7cae122008-07-26 21:49:38143// The supported severity levels for macros that allow you to specify one
[email protected]f2c05492014-06-17 12:04:23144// are (in increasing order of severity) INFO, WARNING, ERROR, and FATAL.
initial.commitd7cae122008-07-26 21:49:38145//
146// Very important: logging a message at the FATAL severity level causes
147// the program to terminate (after the message is logged).
[email protected]fb62a532009-02-12 01:19:05148//
[email protected]f2c05492014-06-17 12:04:23149// There is the special severity of DFATAL, which logs FATAL in debug mode,
150// ERROR in normal mode.
Rob Schonberger45637212018-12-03 04:46:25151//
152// Output is of the format, for example:
153// [3816:3877:0812/234555.406952:VERBOSE1:drm_device_handle.cc(90)] Succeeded
154// authenticating /dev/dri/card0 in 0 ms with 1 attempt(s)
155//
156// The colon separated fields inside the brackets are as follows:
157// 0. An optional Logfile prefix (not included in this example)
158// 1. Process ID
159// 2. Thread ID
160// 3. The date/time of the log message, in MMDD/HHMMSS.Milliseconds format
161// 4. The log level
162// 5. The filename and line number where the log was instantiated
163//
164// Note that the visibility can be changed by setting preferences in
165// SetLogItems()
initial.commitd7cae122008-07-26 21:49:38166
167namespace logging {
168
[email protected]5e3f7c22013-06-21 21:15:33169// TODO(avi): do we want to do a unification of character types here?
170#if defined(OS_WIN)
jdoerrie5c4dc4e2019-02-01 18:02:33171typedef base::char16 PathChar;
Fabrice de Gans-Riberi306871de2018-05-16 19:38:39172#elif defined(OS_POSIX) || defined(OS_FUCHSIA)
[email protected]5e3f7c22013-06-21 21:15:33173typedef char PathChar;
174#endif
175
Sharon Yang7cb919a2019-05-20 20:27:15176// A bitmask of potential logging destinations.
177using LoggingDestination = uint32_t;
178// Specifies where logs will be written. Multiple destinations can be specified
179// with bitwise OR.
180// Unless destination is LOG_NONE, all logs with severity ERROR and above will
181// be written to stderr in addition to the specified destination.
182enum : uint32_t {
[email protected]5e3f7c22013-06-21 21:15:33183 LOG_NONE = 0,
184 LOG_TO_FILE = 1 << 0,
185 LOG_TO_SYSTEM_DEBUG_LOG = 1 << 1,
Sharon Yang7cb919a2019-05-20 20:27:15186 LOG_TO_STDERR = 1 << 2,
[email protected]5e3f7c22013-06-21 21:15:33187
Sharon Yang7cb919a2019-05-20 20:27:15188 LOG_TO_ALL = LOG_TO_FILE | LOG_TO_SYSTEM_DEBUG_LOG | LOG_TO_STDERR,
[email protected]5e3f7c22013-06-21 21:15:33189
Sharon Yang7cb919a2019-05-20 20:27:15190// On Windows, use a file next to the exe.
191// On POSIX platforms, where it may not even be possible to locate the
192// executable on disk, use stderr.
193// On Fuchsia, use the Fuchsia logging service.
194#if defined(OS_FUCHSIA) || defined(OS_NACL)
[email protected]5e3f7c22013-06-21 21:15:33195 LOG_DEFAULT = LOG_TO_SYSTEM_DEBUG_LOG,
Sharon Yang7cb919a2019-05-20 20:27:15196#elif defined(OS_WIN)
197 LOG_DEFAULT = LOG_TO_FILE,
198#elif defined(OS_POSIX)
199 LOG_DEFAULT = LOG_TO_SYSTEM_DEBUG_LOG | LOG_TO_STDERR,
[email protected]5e3f7c22013-06-21 21:15:33200#endif
201};
initial.commitd7cae122008-07-26 21:49:38202
203// Indicates that the log file should be locked when being written to.
[email protected]5e3f7c22013-06-21 21:15:33204// Unless there is only one single-threaded process that is logging to
205// the log file, the file should be locked during writes to make each
[email protected]3ee50d12014-03-05 01:43:27206// log output atomic. Other writers will block.
initial.commitd7cae122008-07-26 21:49:38207//
208// All processes writing to the log file must have their locking set for it to
[email protected]5e3f7c22013-06-21 21:15:33209// work properly. Defaults to LOCK_LOG_FILE.
initial.commitd7cae122008-07-26 21:49:38210enum LogLockingState { LOCK_LOG_FILE, DONT_LOCK_LOG_FILE };
211
212// On startup, should we delete or append to an existing log file (if any)?
213// Defaults to APPEND_TO_OLD_LOG_FILE.
214enum OldFileDeletionState { DELETE_OLD_LOG_FILE, APPEND_TO_OLD_LOG_FILE };
215
[email protected]5e3f7c22013-06-21 21:15:33216struct BASE_EXPORT LoggingSettings {
Sharon Yang7cb919a2019-05-20 20:27:15217 // Equivalent to logging destination enum, but allows for multiple
218 // destinations.
Wez7e125622019-05-29 22:11:28219 uint32_t logging_dest = LOG_DEFAULT;
[email protected]5e3f7c22013-06-21 21:15:33220
Robbie McElrath8bf49842019-08-20 22:22:53221 // The four settings below have an effect only when LOG_TO_FILE is
[email protected]5e3f7c22013-06-21 21:15:33222 // set in |logging_dest|.
Robbie McElrath8bf49842019-08-20 22:22:53223 const PathChar* log_file_path = nullptr;
Wez7e125622019-05-29 22:11:28224 LogLockingState lock_log = LOCK_LOG_FILE;
225 OldFileDeletionState delete_old = APPEND_TO_OLD_LOG_FILE;
Robbie McElrath8bf49842019-08-20 22:22:53226#if defined(OS_CHROMEOS)
227 // Contains an optional file that logs should be written to. If present,
228 // |log_file_path| will be ignored, and the logging system will take ownership
229 // of the FILE. If there's an error writing to this file, no fallback paths
230 // will be opened.
231 FILE* log_file = nullptr;
232#endif
[email protected]5e3f7c22013-06-21 21:15:33233};
[email protected]ff3d0c32010-08-23 19:57:46234
235// Define different names for the BaseInitLoggingImpl() function depending on
236// whether NDEBUG is defined or not so that we'll fail to link if someone tries
237// to compile logging.cc with NDEBUG but includes logging.h without defining it,
238// or vice versa.
weza245bd072017-06-18 23:26:34239#if defined(NDEBUG)
[email protected]ff3d0c32010-08-23 19:57:46240#define BaseInitLoggingImpl BaseInitLoggingImpl_built_with_NDEBUG
241#else
242#define BaseInitLoggingImpl BaseInitLoggingImpl_built_without_NDEBUG
243#endif
244
245// Implementation of the InitLogging() method declared below. We use a
246// more-specific name so we can #define it above without affecting other code
247// that has named stuff "InitLogging".
[email protected]5e3f7c22013-06-21 21:15:33248BASE_EXPORT bool BaseInitLoggingImpl(const LoggingSettings& settings);
[email protected]ff3d0c32010-08-23 19:57:46249
initial.commitd7cae122008-07-26 21:49:38250// Sets the log file name and other global logging state. Calling this function
251// is recommended, and is normally done at the beginning of application init.
252// If you don't call it, all the flags will be initialized to their default
253// values, and there is a race condition that may leak a critical section
254// object if two threads try to do the first log at the same time.
255// See the definition of the enums above for descriptions and default values.
256//
257// The default log file is initialized to "debug.log" in the application
258// directory. You probably don't want this, especially since the program
259// directory may not be writable on an enduser's system.
[email protected]064aa162011-12-03 00:30:08260//
261// This function may be called a second time to re-direct logging (e.g after
262// loging in to a user partition), however it should never be called more than
263// twice.
[email protected]5e3f7c22013-06-21 21:15:33264inline bool InitLogging(const LoggingSettings& settings) {
265 return BaseInitLoggingImpl(settings);
[email protected]ff3d0c32010-08-23 19:57:46266}
initial.commitd7cae122008-07-26 21:49:38267
268// Sets the log level. Anything at or above this level will be written to the
269// log file/displayed to the user (if applicable). Anything below this level
[email protected]162ac0f2010-11-04 15:50:49270// will be silently ignored. The log level defaults to 0 (everything is logged
271// up to level INFO) if this function is not called.
272// Note that log messages for VLOG(x) are logged at level -x, so setting
273// the min log level to negative values enables verbose logging.
[email protected]0bea7252011-08-05 15:34:00274BASE_EXPORT void SetMinLogLevel(int level);
initial.commitd7cae122008-07-26 21:49:38275
[email protected]8a2986ca2009-04-10 19:13:42276// Gets the current log level.
[email protected]0bea7252011-08-05 15:34:00277BASE_EXPORT int GetMinLogLevel();
initial.commitd7cae122008-07-26 21:49:38278
skobesc78c0ad72015-12-07 20:21:23279// Used by LOG_IS_ON to lazy-evaluate stream arguments.
280BASE_EXPORT bool ShouldCreateLogMessage(int severity);
281
[email protected]162ac0f2010-11-04 15:50:49282// Gets the VLOG default verbosity level.
[email protected]0bea7252011-08-05 15:34:00283BASE_EXPORT int GetVlogVerbosity();
[email protected]162ac0f2010-11-04 15:50:49284
[email protected]2f4e9a62010-09-29 21:25:14285// Note that |N| is the size *with* the null terminator.
[email protected]0bea7252011-08-05 15:34:00286BASE_EXPORT int GetVlogLevelHelper(const char* file_start, size_t N);
[email protected]2f4e9a62010-09-29 21:25:14287
tnagel270da922017-05-24 12:10:44288// Gets the current vlog level for the given file (usually taken from __FILE__).
[email protected]99b7c57f2010-09-29 19:26:36289template <size_t N>
290int GetVlogLevel(const char (&file)[N]) {
291 return GetVlogLevelHelper(file, N);
292}
initial.commitd7cae122008-07-26 21:49:38293
294// Sets the common items you want to be prepended to each log message.
295// process and thread IDs default to off, the timestamp defaults to on.
296// If this function is not called, logging defaults to writing the timestamp
297// only.
[email protected]0bea7252011-08-05 15:34:00298BASE_EXPORT void SetLogItems(bool enable_process_id, bool enable_thread_id,
299 bool enable_timestamp, bool enable_tickcount);
initial.commitd7cae122008-07-26 21:49:38300
James Cooka0536c32018-08-01 20:13:31301// Sets an optional prefix to add to each log message. |prefix| is not copied
302// and should be a raw string constant. |prefix| must only contain ASCII letters
303// to avoid confusion with PIDs and timestamps. Pass null to remove the prefix.
304// Logging defaults to no prefix.
305BASE_EXPORT void SetLogPrefix(const char* prefix);
306
[email protected]81e0a852010-08-17 00:38:12307// Sets whether or not you'd like to see fatal debug messages popped up in
308// a dialog box or not.
309// Dialogs are not shown by default.
[email protected]0bea7252011-08-05 15:34:00310BASE_EXPORT void SetShowErrorDialogs(bool enable_dialogs);
[email protected]81e0a852010-08-17 00:38:12311
initial.commitd7cae122008-07-26 21:49:38312// Sets the Log Assert Handler that will be used to notify of check failures.
alex-accc1bde62017-04-19 08:33:55313// Resets Log Assert Handler on object destruction.
[email protected]fb62a532009-02-12 01:19:05314// The default handler shows a dialog box and then terminate the process,
315// however clients can use this function to override with their own handling
316// (e.g. a silent one for Unit Tests)
alex-accc1bde62017-04-19 08:33:55317using LogAssertHandlerFunction =
kylechar83fb51e52019-03-14 15:30:43318 base::RepeatingCallback<void(const char* file,
319 int line,
320 const base::StringPiece message,
321 const base::StringPiece stack_trace)>;
alex-accc1bde62017-04-19 08:33:55322
323class BASE_EXPORT ScopedLogAssertHandler {
324 public:
325 explicit ScopedLogAssertHandler(LogAssertHandlerFunction handler);
326 ~ScopedLogAssertHandler();
327
328 private:
329 DISALLOW_COPY_AND_ASSIGN(ScopedLogAssertHandler);
330};
[email protected]64e5cc02010-11-03 19:20:27331
[email protected]2b07b8412009-11-25 15:26:34332// Sets the Log Message Handler that gets passed every log message before
333// it's sent to other log destinations (if any).
334// Returns true to signal that it handled the message and the message
335// should not be sent to other log destinations.
[email protected]162ac0f2010-11-04 15:50:49336typedef bool (*LogMessageHandlerFunction)(int severity,
337 const char* file, int line, size_t message_start, const std::string& str);
[email protected]0bea7252011-08-05 15:34:00338BASE_EXPORT void SetLogMessageHandler(LogMessageHandlerFunction handler);
339BASE_EXPORT LogMessageHandlerFunction GetLogMessageHandler();
[email protected]2b07b8412009-11-25 15:26:34340
kmarshallfe2f09f82017-04-20 21:05:26341// The ANALYZER_ASSUME_TRUE(bool arg) macro adds compiler-specific hints
342// to Clang which control what code paths are statically analyzed,
343// and is meant to be used in conjunction with assert & assert-like functions.
344// The expression is passed straight through if analysis isn't enabled.
Kevin Marshall7273edd2017-06-20 22:19:36345//
346// ANALYZER_SKIP_THIS_PATH() suppresses static analysis for the current
347// codepath and any other branching codepaths that might follow.
kmarshallfe2f09f82017-04-20 21:05:26348#if defined(__clang_analyzer__)
349
350inline constexpr bool AnalyzerNoReturn() __attribute__((analyzer_noreturn)) {
351 return false;
352}
353
354inline constexpr bool AnalyzerAssumeTrue(bool arg) {
355 // AnalyzerNoReturn() is invoked and analysis is terminated if |arg| is
356 // false.
357 return arg || AnalyzerNoReturn();
358}
359
Kevin Marshall7273edd2017-06-20 22:19:36360#define ANALYZER_ASSUME_TRUE(arg) logging::AnalyzerAssumeTrue(!!(arg))
361#define ANALYZER_SKIP_THIS_PATH() \
362 static_cast<void>(::logging::AnalyzerNoReturn())
Kevin Marshall089565ec2017-07-13 02:57:21363#define ANALYZER_ALLOW_UNUSED(var) static_cast<void>(var);
kmarshallfe2f09f82017-04-20 21:05:26364
365#else // !defined(__clang_analyzer__)
366
367#define ANALYZER_ASSUME_TRUE(arg) (arg)
Kevin Marshall7273edd2017-06-20 22:19:36368#define ANALYZER_SKIP_THIS_PATH()
Kevin Marshall089565ec2017-07-13 02:57:21369#define ANALYZER_ALLOW_UNUSED(var) static_cast<void>(var);
kmarshallfe2f09f82017-04-20 21:05:26370
371#endif // defined(__clang_analyzer__)
372
initial.commitd7cae122008-07-26 21:49:38373typedef int LogSeverity;
[email protected]162ac0f2010-11-04 15:50:49374const LogSeverity LOG_VERBOSE = -1; // This is level 1 verbosity
375// Note: the log severities are used to index into the array of names,
376// see log_severity_names.
initial.commitd7cae122008-07-26 21:49:38377const LogSeverity LOG_INFO = 0;
378const LogSeverity LOG_WARNING = 1;
379const LogSeverity LOG_ERROR = 2;
[email protected]f2c05492014-06-17 12:04:23380const LogSeverity LOG_FATAL = 3;
381const LogSeverity LOG_NUM_SEVERITIES = 4;
initial.commitd7cae122008-07-26 21:49:38382
[email protected]521b0c42010-10-01 23:02:36383// LOG_DFATAL is LOG_FATAL in debug mode, ERROR in normal mode
weza245bd072017-06-18 23:26:34384#if defined(NDEBUG)
[email protected]521b0c42010-10-01 23:02:36385const LogSeverity LOG_DFATAL = LOG_ERROR;
initial.commitd7cae122008-07-26 21:49:38386#else
[email protected]521b0c42010-10-01 23:02:36387const LogSeverity LOG_DFATAL = LOG_FATAL;
initial.commitd7cae122008-07-26 21:49:38388#endif
389
390// A few definitions of macros that don't generate much code. These are used
391// by LOG() and LOG_IF, etc. Since these are used all over our code, it's
392// better to have compact code for these operations.
[email protected]d8617a62009-10-09 23:52:20393#define COMPACT_GOOGLE_LOG_EX_INFO(ClassName, ...) \
tsniatowski612550f2016-07-21 18:26:20394 ::logging::ClassName(__FILE__, __LINE__, ::logging::LOG_INFO, ##__VA_ARGS__)
395#define COMPACT_GOOGLE_LOG_EX_WARNING(ClassName, ...) \
396 ::logging::ClassName(__FILE__, __LINE__, ::logging::LOG_WARNING, \
397 ##__VA_ARGS__)
[email protected]d8617a62009-10-09 23:52:20398#define COMPACT_GOOGLE_LOG_EX_ERROR(ClassName, ...) \
tsniatowski612550f2016-07-21 18:26:20399 ::logging::ClassName(__FILE__, __LINE__, ::logging::LOG_ERROR, ##__VA_ARGS__)
[email protected]d8617a62009-10-09 23:52:20400#define COMPACT_GOOGLE_LOG_EX_FATAL(ClassName, ...) \
tsniatowski612550f2016-07-21 18:26:20401 ::logging::ClassName(__FILE__, __LINE__, ::logging::LOG_FATAL, ##__VA_ARGS__)
[email protected]d8617a62009-10-09 23:52:20402#define COMPACT_GOOGLE_LOG_EX_DFATAL(ClassName, ...) \
tsniatowski612550f2016-07-21 18:26:20403 ::logging::ClassName(__FILE__, __LINE__, ::logging::LOG_DFATAL, ##__VA_ARGS__)
Wez289477f2017-08-24 20:51:30404#define COMPACT_GOOGLE_LOG_EX_DCHECK(ClassName, ...) \
405 ::logging::ClassName(__FILE__, __LINE__, ::logging::LOG_DCHECK, ##__VA_ARGS__)
[email protected]d8617a62009-10-09 23:52:20406
Wez289477f2017-08-24 20:51:30407#define COMPACT_GOOGLE_LOG_INFO COMPACT_GOOGLE_LOG_EX_INFO(LogMessage)
408#define COMPACT_GOOGLE_LOG_WARNING COMPACT_GOOGLE_LOG_EX_WARNING(LogMessage)
409#define COMPACT_GOOGLE_LOG_ERROR COMPACT_GOOGLE_LOG_EX_ERROR(LogMessage)
410#define COMPACT_GOOGLE_LOG_FATAL COMPACT_GOOGLE_LOG_EX_FATAL(LogMessage)
411#define COMPACT_GOOGLE_LOG_DFATAL COMPACT_GOOGLE_LOG_EX_DFATAL(LogMessage)
412#define COMPACT_GOOGLE_LOG_DCHECK COMPACT_GOOGLE_LOG_EX_DCHECK(LogMessage)
initial.commitd7cae122008-07-26 21:49:38413
[email protected]8d127302013-01-10 02:41:57414#if defined(OS_WIN)
initial.commitd7cae122008-07-26 21:49:38415// wingdi.h defines ERROR to be 0. When we call LOG(ERROR), it gets
416// substituted with 0, and it expands to COMPACT_GOOGLE_LOG_0. To allow us
417// to keep using this syntax, we define this macro to do the same thing
418// as COMPACT_GOOGLE_LOG_ERROR, and also define ERROR the same way that
419// the Windows SDK does for consistency.
420#define ERROR 0
[email protected]d8617a62009-10-09 23:52:20421#define COMPACT_GOOGLE_LOG_EX_0(ClassName, ...) \
422 COMPACT_GOOGLE_LOG_EX_ERROR(ClassName , ##__VA_ARGS__)
423#define COMPACT_GOOGLE_LOG_0 COMPACT_GOOGLE_LOG_ERROR
[email protected]521b0c42010-10-01 23:02:36424// Needed for LOG_IS_ON(ERROR).
425const LogSeverity LOG_0 = LOG_ERROR;
[email protected]8d127302013-01-10 02:41:57426#endif
[email protected]521b0c42010-10-01 23:02:36427
[email protected]f2c05492014-06-17 12:04:23428// As special cases, we can assume that LOG_IS_ON(FATAL) always holds. Also,
429// LOG_IS_ON(DFATAL) always holds in debug mode. In particular, CHECK()s will
430// always fire if they fail.
[email protected]521b0c42010-10-01 23:02:36431#define LOG_IS_ON(severity) \
skobesc78c0ad72015-12-07 20:21:23432 (::logging::ShouldCreateLogMessage(::logging::LOG_##severity))
[email protected]521b0c42010-10-01 23:02:36433
Ken MacKay70e8867002019-01-16 00:22:15434// We don't do any caching tricks with VLOG_IS_ON() like the
435// google-glog version since it increases binary size. This means
[email protected]521b0c42010-10-01 23:02:36436// that using the v-logging functions in conjunction with --vmodule
437// may be slow.
438#define VLOG_IS_ON(verboselevel) \
439 ((verboselevel) <= ::logging::GetVlogLevel(__FILE__))
440
441// Helper macro which avoids evaluating the arguments to a stream if
chcunninghamf6a96082015-02-07 01:58:37442// the condition doesn't hold. Condition is evaluated once and only once.
[email protected]521b0c42010-10-01 23:02:36443#define LAZY_STREAM(stream, condition) \
444 !(condition) ? (void) 0 : ::logging::LogMessageVoidify() & (stream)
initial.commitd7cae122008-07-26 21:49:38445
446// We use the preprocessor's merging operator, "##", so that, e.g.,
447// LOG(INFO) becomes the token COMPACT_GOOGLE_LOG_INFO. There's some funny
448// subtle difference between ostream member streaming functions (e.g.,
449// ostream::operator<<(int) and ostream non-member streaming functions
450// (e.g., ::operator<<(ostream&, string&): it turns out that it's
451// impossible to stream something like a string directly to an unnamed
452// ostream. We employ a neat hack by calling the stream() member
453// function of LogMessage which seems to avoid the problem.
[email protected]521b0c42010-10-01 23:02:36454#define LOG_STREAM(severity) COMPACT_GOOGLE_LOG_ ## severity.stream()
initial.commitd7cae122008-07-26 21:49:38455
[email protected]521b0c42010-10-01 23:02:36456#define LOG(severity) LAZY_STREAM(LOG_STREAM(severity), LOG_IS_ON(severity))
457#define LOG_IF(severity, condition) \
458 LAZY_STREAM(LOG_STREAM(severity), LOG_IS_ON(severity) && (condition))
459
[email protected]162ac0f2010-11-04 15:50:49460// The VLOG macros log with negative verbosities.
461#define VLOG_STREAM(verbose_level) \
tsniatowski612550f2016-07-21 18:26:20462 ::logging::LogMessage(__FILE__, __LINE__, -verbose_level).stream()
[email protected]162ac0f2010-11-04 15:50:49463
464#define VLOG(verbose_level) \
465 LAZY_STREAM(VLOG_STREAM(verbose_level), VLOG_IS_ON(verbose_level))
466
467#define VLOG_IF(verbose_level, condition) \
468 LAZY_STREAM(VLOG_STREAM(verbose_level), \
469 VLOG_IS_ON(verbose_level) && (condition))
[email protected]99b7c57f2010-09-29 19:26:36470
[email protected]fb879b1a2011-03-06 18:16:31471#if defined (OS_WIN)
472#define VPLOG_STREAM(verbose_level) \
tsniatowski612550f2016-07-21 18:26:20473 ::logging::Win32ErrorLogMessage(__FILE__, __LINE__, -verbose_level, \
[email protected]fb879b1a2011-03-06 18:16:31474 ::logging::GetLastSystemErrorCode()).stream()
Fabrice de Gans-Riberi306871de2018-05-16 19:38:39475#elif defined(OS_POSIX) || defined(OS_FUCHSIA)
[email protected]fb879b1a2011-03-06 18:16:31476#define VPLOG_STREAM(verbose_level) \
tsniatowski612550f2016-07-21 18:26:20477 ::logging::ErrnoLogMessage(__FILE__, __LINE__, -verbose_level, \
[email protected]fb879b1a2011-03-06 18:16:31478 ::logging::GetLastSystemErrorCode()).stream()
479#endif
480
481#define VPLOG(verbose_level) \
482 LAZY_STREAM(VPLOG_STREAM(verbose_level), VLOG_IS_ON(verbose_level))
483
484#define VPLOG_IF(verbose_level, condition) \
485 LAZY_STREAM(VPLOG_STREAM(verbose_level), \
486 VLOG_IS_ON(verbose_level) && (condition))
487
[email protected]99b7c57f2010-09-29 19:26:36488// TODO(akalin): Add more VLOG variants, e.g. VPLOG.
initial.commitd7cae122008-07-26 21:49:38489
kmarshallfe2f09f82017-04-20 21:05:26490#define LOG_ASSERT(condition) \
491 LOG_IF(FATAL, !(ANALYZER_ASSUME_TRUE(condition))) \
492 << "Assert failed: " #condition ". "
initial.commitd7cae122008-07-26 21:49:38493
[email protected]d8617a62009-10-09 23:52:20494#if defined(OS_WIN)
[email protected]c914d8a2014-04-23 01:11:01495#define PLOG_STREAM(severity) \
[email protected]d8617a62009-10-09 23:52:20496 COMPACT_GOOGLE_LOG_EX_ ## severity(Win32ErrorLogMessage, \
497 ::logging::GetLastSystemErrorCode()).stream()
Fabrice de Gans-Riberi306871de2018-05-16 19:38:39498#elif defined(OS_POSIX) || defined(OS_FUCHSIA)
[email protected]c914d8a2014-04-23 01:11:01499#define PLOG_STREAM(severity) \
[email protected]d8617a62009-10-09 23:52:20500 COMPACT_GOOGLE_LOG_EX_ ## severity(ErrnoLogMessage, \
501 ::logging::GetLastSystemErrorCode()).stream()
[email protected]d8617a62009-10-09 23:52:20502#endif
503
[email protected]521b0c42010-10-01 23:02:36504#define PLOG(severity) \
505 LAZY_STREAM(PLOG_STREAM(severity), LOG_IS_ON(severity))
506
[email protected]d8617a62009-10-09 23:52:20507#define PLOG_IF(severity, condition) \
[email protected]521b0c42010-10-01 23:02:36508 LAZY_STREAM(PLOG_STREAM(severity), LOG_IS_ON(severity) && (condition))
[email protected]d8617a62009-10-09 23:52:20509
scottmg3c957a52016-12-10 20:57:59510BASE_EXPORT extern std::ostream* g_swallow_stream;
511
512// Note that g_swallow_stream is used instead of an arbitrary LOG() stream to
513// avoid the creation of an object with a non-trivial destructor (LogMessage).
514// On MSVC x86 (checked on 2015 Update 3), this causes a few additional
515// pointless instructions to be emitted even at full optimization level, even
516// though the : arm of the ternary operator is clearly never executed. Using a
517// simpler object to be &'d with Voidify() avoids these extra instructions.
518// Using a simpler POD object with a templated operator<< also works to avoid
519// these instructions. However, this causes warnings on statically defined
520// implementations of operator<<(std::ostream, ...) in some .cc files, because
521// they become defined-but-unreferenced functions. A reinterpret_cast of 0 to an
522// ostream* also is not suitable, because some compilers warn of undefined
523// behavior.
524#define EAT_STREAM_PARAMETERS \
525 true ? (void)0 \
526 : ::logging::LogMessageVoidify() & (*::logging::g_swallow_stream)
[email protected]ddb9b332011-12-02 07:31:09527
erikwright6ad937b2015-07-22 20:05:52528// Captures the result of a CHECK_EQ (for example) and facilitates testing as a
529// boolean.
530class CheckOpResult {
531 public:
wezf01a9b72016-03-19 01:18:07532 // |message| must be non-null if and only if the check failed.
erikwright6ad937b2015-07-22 20:05:52533 CheckOpResult(std::string* message) : message_(message) {}
534 // Returns true if the check succeeded.
535 operator bool() const { return !message_; }
536 // Returns the message.
537 std::string* message() { return message_; }
538
539 private:
540 std::string* message_;
541};
542
initial.commitd7cae122008-07-26 21:49:38543// CHECK dies with a fatal error if condition is not true. It is *not*
544// controlled by NDEBUG, so the check will be executed regardless of
545// compilation mode.
[email protected]521b0c42010-10-01 23:02:36546//
547// We make sure CHECK et al. always evaluates their arguments, as
548// doing CHECK(FunctionWithSideEffect()) is a common idiom.
[email protected]ddb9b332011-12-02 07:31:09549
danakjb9d59312016-05-04 20:06:31550#if defined(OFFICIAL_BUILD) && defined(NDEBUG)
[email protected]ddb9b332011-12-02 07:31:09551
Chris Palmer61343b02016-11-29 20:44:10552// Make all CHECK functions discard their log strings to reduce code bloat, and
553// improve performance, for official release builds.
554//
primianoba910a62016-07-07 22:14:48555// This is not calling BreakDebugger since this is called frequently, and
556// calling an out-of-line function instead of a noreturn inline macro prevents
557// compiler optimizations.
Chris Palmer61343b02016-11-29 20:44:10558#define CHECK(condition) \
danakjcb7c5292016-12-20 19:05:35559 UNLIKELY(!(condition)) ? IMMEDIATE_CRASH() : EAT_STREAM_PARAMETERS
[email protected]ddb9b332011-12-02 07:31:09560
Robert Sesekd2f495f2017-07-25 22:03:14561// PCHECK includes the system error code, which is useful for determining
562// why the condition failed. In official builds, preserve only the error code
563// message so that it is available in crash reports. The stringified
564// condition and any additional stream parameters are dropped.
565#define PCHECK(condition) \
566 LAZY_STREAM(PLOG_STREAM(FATAL), UNLIKELY(!(condition))); \
567 EAT_STREAM_PARAMETERS
[email protected]ddb9b332011-12-02 07:31:09568
569#define CHECK_OP(name, op, val1, val2) CHECK((val1) op (val2))
570
danakjb9d59312016-05-04 20:06:31571#else // !(OFFICIAL_BUILD && NDEBUG)
[email protected]ddb9b332011-12-02 07:31:09572
tnagel4a045d3f2015-07-12 14:19:28573// Do as much work as possible out of line to reduce inline code size.
tsniatowski612550f2016-07-21 18:26:20574#define CHECK(condition) \
575 LAZY_STREAM(::logging::LogMessage(__FILE__, __LINE__, #condition).stream(), \
kmarshallfe2f09f82017-04-20 21:05:26576 !ANALYZER_ASSUME_TRUE(condition))
initial.commitd7cae122008-07-26 21:49:38577
kmarshallfe2f09f82017-04-20 21:05:26578#define PCHECK(condition) \
579 LAZY_STREAM(PLOG_STREAM(FATAL), !ANALYZER_ASSUME_TRUE(condition)) \
kmarshalle23eed02017-02-11 02:13:23580 << "Check failed: " #condition ". "
brucedawson9d160252014-10-23 20:14:14581
[email protected]ddb9b332011-12-02 07:31:09582// Helper macro for binary operators.
583// Don't use this macro directly in your code, use CHECK_EQ et al below.
erikwright6ad937b2015-07-22 20:05:52584// The 'switch' is used to prevent the 'else' from being ambiguous when the
585// macro is used in an 'if' clause such as:
586// if (a == 1)
587// CHECK_EQ(2, a);
588#define CHECK_OP(name, op, val1, val2) \
589 switch (0) case 0: default: \
tsniatowski612550f2016-07-21 18:26:20590 if (::logging::CheckOpResult true_if_passed = \
591 ::logging::Check##name##Impl((val1), (val2), \
592 #val1 " " #op " " #val2)) \
erikwright6ad937b2015-07-22 20:05:52593 ; \
594 else \
tsniatowski612550f2016-07-21 18:26:20595 ::logging::LogMessage(__FILE__, __LINE__, true_if_passed.message()).stream()
[email protected]ddb9b332011-12-02 07:31:09596
danakjb9d59312016-05-04 20:06:31597#endif // !(OFFICIAL_BUILD && NDEBUG)
[email protected]ddb9b332011-12-02 07:31:09598
brucedawson93a60b8c2016-04-28 20:46:16599// This formats a value for a failing CHECK_XX statement. Ordinarily,
600// it uses the definition for operator<<, with a few special cases below.
601template <typename T>
jbroman6bcfec422016-05-26 00:28:46602inline typename std::enable_if<
raphael.kubo.da.costa81f21202016-11-28 18:36:36603 base::internal::SupportsOstreamOperator<const T&>::value &&
604 !std::is_function<typename std::remove_pointer<T>::type>::value,
jbroman6bcfec422016-05-26 00:28:46605 void>::type
606MakeCheckOpValueString(std::ostream* os, const T& v) {
brucedawson93a60b8c2016-04-28 20:46:16607 (*os) << v;
608}
609
Collin Baker89e9e072019-06-10 22:39:05610// Overload for types that no operator<< but do have .ToString() defined.
611template <typename T>
612inline typename std::enable_if<
613 !base::internal::SupportsOstreamOperator<const T&>::value &&
614 base::internal::SupportsToString<const T&>::value,
615 void>::type
616MakeCheckOpValueString(std::ostream* os, const T& v) {
617 (*os) << v.ToString();
618}
619
raphael.kubo.da.costa81f21202016-11-28 18:36:36620// Provide an overload for functions and function pointers. Function pointers
621// don't implicitly convert to void* but do implicitly convert to bool, so
622// without this function pointers are always printed as 1 or 0. (MSVC isn't
623// standards-conforming here and converts function pointers to regular
624// pointers, so this is a no-op for MSVC.)
625template <typename T>
626inline typename std::enable_if<
627 std::is_function<typename std::remove_pointer<T>::type>::value,
628 void>::type
629MakeCheckOpValueString(std::ostream* os, const T& v) {
630 (*os) << reinterpret_cast<const void*>(v);
631}
632
jbroman6bcfec422016-05-26 00:28:46633// We need overloads for enums that don't support operator<<.
634// (i.e. scoped enums where no operator<< overload was declared).
635template <typename T>
636inline typename std::enable_if<
637 !base::internal::SupportsOstreamOperator<const T&>::value &&
638 std::is_enum<T>::value,
639 void>::type
640MakeCheckOpValueString(std::ostream* os, const T& v) {
danakj6d0446e52017-04-05 16:22:29641 (*os) << static_cast<typename std::underlying_type<T>::type>(v);
jbroman6bcfec422016-05-26 00:28:46642}
643
644// We need an explicit overload for std::nullptr_t.
645BASE_EXPORT void MakeCheckOpValueString(std::ostream* os, std::nullptr_t p);
brucedawson93a60b8c2016-04-28 20:46:16646
initial.commitd7cae122008-07-26 21:49:38647// Build the error message string. This is separate from the "Impl"
648// function template because it is not performance critical and so can
[email protected]9c7132e2011-02-08 07:39:08649// be out of line, while the "Impl" code should be inline. Caller
650// takes ownership of the returned string.
initial.commitd7cae122008-07-26 21:49:38651template<class t1, class t2>
652std::string* MakeCheckOpString(const t1& v1, const t2& v2, const char* names) {
653 std::ostringstream ss;
brucedawson93a60b8c2016-04-28 20:46:16654 ss << names << " (";
655 MakeCheckOpValueString(&ss, v1);
656 ss << " vs. ";
657 MakeCheckOpValueString(&ss, v2);
658 ss << ")";
initial.commitd7cae122008-07-26 21:49:38659 std::string* msg = new std::string(ss.str());
660 return msg;
661}
662
[email protected]6d445d32010-09-30 19:10:03663// Commonly used instantiations of MakeCheckOpString<>. Explicitly instantiated
664// in logging.cc.
[email protected]dc72da32011-10-24 20:20:30665extern template BASE_EXPORT std::string* MakeCheckOpString<int, int>(
[email protected]6d445d32010-09-30 19:10:03666 const int&, const int&, const char* names);
[email protected]dc72da32011-10-24 20:20:30667extern template BASE_EXPORT
668std::string* MakeCheckOpString<unsigned long, unsigned long>(
[email protected]6d445d32010-09-30 19:10:03669 const unsigned long&, const unsigned long&, const char* names);
[email protected]dc72da32011-10-24 20:20:30670extern template BASE_EXPORT
671std::string* MakeCheckOpString<unsigned long, unsigned int>(
[email protected]6d445d32010-09-30 19:10:03672 const unsigned long&, const unsigned int&, const char* names);
[email protected]dc72da32011-10-24 20:20:30673extern template BASE_EXPORT
674std::string* MakeCheckOpString<unsigned int, unsigned long>(
[email protected]6d445d32010-09-30 19:10:03675 const unsigned int&, const unsigned long&, const char* names);
[email protected]dc72da32011-10-24 20:20:30676extern template BASE_EXPORT
677std::string* MakeCheckOpString<std::string, std::string>(
[email protected]6d445d32010-09-30 19:10:03678 const std::string&, const std::string&, const char* name);
initial.commitd7cae122008-07-26 21:49:38679
[email protected]71512602010-11-01 22:19:56680// Helper functions for CHECK_OP macro.
681// The (int, int) specialization works around the issue that the compiler
682// will not instantiate the template version of the function on values of
683// unnamed enum type - see comment below.
kmarshallfe2f09f82017-04-20 21:05:26684//
685// The checked condition is wrapped with ANALYZER_ASSUME_TRUE, which under
686// static analysis builds, blocks analysis of the current path if the
687// condition is false.
kmarshall9db26fb2017-02-15 01:05:33688#define DEFINE_CHECK_OP_IMPL(name, op) \
689 template <class t1, class t2> \
690 inline std::string* Check##name##Impl(const t1& v1, const t2& v2, \
691 const char* names) { \
kmarshallfe2f09f82017-04-20 21:05:26692 if (ANALYZER_ASSUME_TRUE(v1 op v2)) \
kmarshall9db26fb2017-02-15 01:05:33693 return NULL; \
694 else \
695 return ::logging::MakeCheckOpString(v1, v2, names); \
696 } \
[email protected]71512602010-11-01 22:19:56697 inline std::string* Check##name##Impl(int v1, int v2, const char* names) { \
kmarshallfe2f09f82017-04-20 21:05:26698 if (ANALYZER_ASSUME_TRUE(v1 op v2)) \
kmarshall9db26fb2017-02-15 01:05:33699 return NULL; \
700 else \
701 return ::logging::MakeCheckOpString(v1, v2, names); \
[email protected]71512602010-11-01 22:19:56702 }
703DEFINE_CHECK_OP_IMPL(EQ, ==)
704DEFINE_CHECK_OP_IMPL(NE, !=)
705DEFINE_CHECK_OP_IMPL(LE, <=)
706DEFINE_CHECK_OP_IMPL(LT, < )
707DEFINE_CHECK_OP_IMPL(GE, >=)
708DEFINE_CHECK_OP_IMPL(GT, > )
709#undef DEFINE_CHECK_OP_IMPL
[email protected]e150c0382010-03-02 00:41:12710
711#define CHECK_EQ(val1, val2) CHECK_OP(EQ, ==, val1, val2)
712#define CHECK_NE(val1, val2) CHECK_OP(NE, !=, val1, val2)
713#define CHECK_LE(val1, val2) CHECK_OP(LE, <=, val1, val2)
714#define CHECK_LT(val1, val2) CHECK_OP(LT, < , val1, val2)
715#define CHECK_GE(val1, val2) CHECK_OP(GE, >=, val1, val2)
716#define CHECK_GT(val1, val2) CHECK_OP(GT, > , val1, val2)
717
jam121900aa2016-04-19 00:07:34718#if defined(NDEBUG) && !defined(DCHECK_ALWAYS_ON)
danakje649f572015-01-08 23:35:58719#define DCHECK_IS_ON() 0
[email protected]1a1505512014-03-10 18:23:38720#else
danakje649f572015-01-08 23:35:58721#define DCHECK_IS_ON() 1
[email protected]e3cca332009-08-20 01:20:29722#endif
723
[email protected]d15e56c2010-09-30 21:12:33724// Definitions for DLOG et al.
725
gab190f7542016-08-01 20:03:41726#if DCHECK_IS_ON()
[email protected]d926c202010-10-01 02:58:24727
[email protected]5e987802010-11-01 19:49:22728#define DLOG_IS_ON(severity) LOG_IS_ON(severity)
[email protected]d926c202010-10-01 02:58:24729#define DLOG_IF(severity, condition) LOG_IF(severity, condition)
730#define DLOG_ASSERT(condition) LOG_ASSERT(condition)
[email protected]d926c202010-10-01 02:58:24731#define DPLOG_IF(severity, condition) PLOG_IF(severity, condition)
[email protected]521b0c42010-10-01 23:02:36732#define DVLOG_IF(verboselevel, condition) VLOG_IF(verboselevel, condition)
[email protected]fb879b1a2011-03-06 18:16:31733#define DVPLOG_IF(verboselevel, condition) VPLOG_IF(verboselevel, condition)
[email protected]d926c202010-10-01 02:58:24734
gab190f7542016-08-01 20:03:41735#else // DCHECK_IS_ON()
[email protected]d926c202010-10-01 02:58:24736
gab190f7542016-08-01 20:03:41737// If !DCHECK_IS_ON(), we want to avoid emitting any references to |condition|
738// (which may reference a variable defined only if DCHECK_IS_ON()).
739// Contrast this with DCHECK et al., which has different behavior.
[email protected]d926c202010-10-01 02:58:24740
[email protected]5e987802010-11-01 19:49:22741#define DLOG_IS_ON(severity) false
[email protected]ddb9b332011-12-02 07:31:09742#define DLOG_IF(severity, condition) EAT_STREAM_PARAMETERS
743#define DLOG_ASSERT(condition) EAT_STREAM_PARAMETERS
744#define DPLOG_IF(severity, condition) EAT_STREAM_PARAMETERS
745#define DVLOG_IF(verboselevel, condition) EAT_STREAM_PARAMETERS
746#define DVPLOG_IF(verboselevel, condition) EAT_STREAM_PARAMETERS
[email protected]d926c202010-10-01 02:58:24747
gab190f7542016-08-01 20:03:41748#endif // DCHECK_IS_ON()
[email protected]d926c202010-10-01 02:58:24749
[email protected]521b0c42010-10-01 23:02:36750#define DLOG(severity) \
751 LAZY_STREAM(LOG_STREAM(severity), DLOG_IS_ON(severity))
752
[email protected]521b0c42010-10-01 23:02:36753#define DPLOG(severity) \
754 LAZY_STREAM(PLOG_STREAM(severity), DLOG_IS_ON(severity))
755
Ken MacKay70e8867002019-01-16 00:22:15756#define DVLOG(verboselevel) DVLOG_IF(verboselevel, true)
[email protected]521b0c42010-10-01 23:02:36757
Ken MacKay70e8867002019-01-16 00:22:15758#define DVPLOG(verboselevel) DVPLOG_IF(verboselevel, true)
[email protected]fb879b1a2011-03-06 18:16:31759
[email protected]521b0c42010-10-01 23:02:36760// Definitions for DCHECK et al.
[email protected]d926c202010-10-01 02:58:24761
danakje649f572015-01-08 23:35:58762#if DCHECK_IS_ON()
[email protected]e3cca332009-08-20 01:20:29763
Tomas Popelaafffa972018-11-13 20:42:05764#if defined(DCHECK_IS_CONFIGURABLE)
Wez289477f2017-08-24 20:51:30765BASE_EXPORT extern LogSeverity LOG_DCHECK;
766#else
[email protected]521b0c42010-10-01 23:02:36767const LogSeverity LOG_DCHECK = LOG_FATAL;
Tomas Popelaafffa972018-11-13 20:42:05768#endif // defined(DCHECK_IS_CONFIGURABLE)
[email protected]521b0c42010-10-01 23:02:36769
danakje649f572015-01-08 23:35:58770#else // DCHECK_IS_ON()
[email protected]521b0c42010-10-01 23:02:36771
Sigurdur Asgeirsson7013e5f2017-09-29 17:42:58772// There may be users of LOG_DCHECK that are enabled independently
773// of DCHECK_IS_ON(), so default to FATAL logging for those.
774const LogSeverity LOG_DCHECK = LOG_FATAL;
[email protected]521b0c42010-10-01 23:02:36775
danakje649f572015-01-08 23:35:58776#endif // DCHECK_IS_ON()
[email protected]521b0c42010-10-01 23:02:36777
[email protected]deba0ff2010-11-03 05:30:14778// DCHECK et al. make sure to reference |condition| regardless of
[email protected]521b0c42010-10-01 23:02:36779// whether DCHECKs are enabled; this is so that we don't get unused
780// variable warnings if the only use of a variable is in a DCHECK.
781// This behavior is different from DLOG_IF et al.
dchengfc670f472017-01-25 17:48:43782//
783// Note that the definition of the DCHECK macros depends on whether or not
784// DCHECK_IS_ON() is true. When DCHECK_IS_ON() is false, the macros use
785// EAT_STREAM_PARAMETERS to avoid expressions that would create temporaries.
[email protected]521b0c42010-10-01 23:02:36786
dchengfc670f472017-01-25 17:48:43787#if DCHECK_IS_ON()
788
kmarshallfe2f09f82017-04-20 21:05:26789#define DCHECK(condition) \
790 LAZY_STREAM(LOG_STREAM(DCHECK), !ANALYZER_ASSUME_TRUE(condition)) \
dchengfc670f472017-01-25 17:48:43791 << "Check failed: " #condition ". "
kmarshallfe2f09f82017-04-20 21:05:26792#define DPCHECK(condition) \
793 LAZY_STREAM(PLOG_STREAM(DCHECK), !ANALYZER_ASSUME_TRUE(condition)) \
danakje649f572015-01-08 23:35:58794 << "Check failed: " #condition ". "
[email protected]521b0c42010-10-01 23:02:36795
dchengfc670f472017-01-25 17:48:43796#else // DCHECK_IS_ON()
797
kmarshall08c892f72017-02-28 03:46:18798#define DCHECK(condition) EAT_STREAM_PARAMETERS << !(condition)
799#define DPCHECK(condition) EAT_STREAM_PARAMETERS << !(condition)
dchengfc670f472017-01-25 17:48:43800
801#endif // DCHECK_IS_ON()
[email protected]d926c202010-10-01 02:58:24802
803// Helper macro for binary operators.
804// Don't use this macro directly in your code, use DCHECK_EQ et al below.
erikwright6ad937b2015-07-22 20:05:52805// The 'switch' is used to prevent the 'else' from being ambiguous when the
806// macro is used in an 'if' clause such as:
807// if (a == 1)
808// DCHECK_EQ(2, a);
dchengfc670f472017-01-25 17:48:43809#if DCHECK_IS_ON()
810
tsniatowski612550f2016-07-21 18:26:20811#define DCHECK_OP(name, op, val1, val2) \
812 switch (0) case 0: default: \
813 if (::logging::CheckOpResult true_if_passed = \
tsniatowski612550f2016-07-21 18:26:20814 ::logging::Check##name##Impl((val1), (val2), \
Wez6a592ee2018-05-25 20:29:07815 #val1 " " #op " " #val2)) \
tsniatowski612550f2016-07-21 18:26:20816 ; \
817 else \
818 ::logging::LogMessage(__FILE__, __LINE__, ::logging::LOG_DCHECK, \
819 true_if_passed.message()).stream()
initial.commitd7cae122008-07-26 21:49:38820
dchengfc670f472017-01-25 17:48:43821#else // DCHECK_IS_ON()
822
823// When DCHECKs aren't enabled, DCHECK_OP still needs to reference operator<<
824// overloads for |val1| and |val2| to avoid potential compiler warnings about
825// unused functions. For the same reason, it also compares |val1| and |val2|
826// using |op|.
827//
828// Note that the contract of DCHECK_EQ, etc is that arguments are only evaluated
829// once. Even though |val1| and |val2| appear twice in this version of the macro
830// expansion, this is OK, since the expression is never actually evaluated.
831#define DCHECK_OP(name, op, val1, val2) \
832 EAT_STREAM_PARAMETERS << (::logging::MakeCheckOpValueString( \
833 ::logging::g_swallow_stream, val1), \
834 ::logging::MakeCheckOpValueString( \
835 ::logging::g_swallow_stream, val2), \
kmarshall08c892f72017-02-28 03:46:18836 (val1)op(val2))
dchengfc670f472017-01-25 17:48:43837
838#endif // DCHECK_IS_ON()
839
[email protected]deba0ff2010-11-03 05:30:14840// Equality/Inequality checks - compare two values, and log a
841// LOG_DCHECK message including the two values when the result is not
842// as expected. The values must have operator<<(ostream, ...)
843// defined.
initial.commitd7cae122008-07-26 21:49:38844//
845// You may append to the error message like so:
pwnall7ae42b462016-09-22 02:26:12846// DCHECK_NE(1, 2) << "The world must be ending!";
initial.commitd7cae122008-07-26 21:49:38847//
848// We are very careful to ensure that each argument is evaluated exactly
849// once, and that anything which is legal to pass as a function argument is
850// legal here. In particular, the arguments may be temporary expressions
851// which will end up being destroyed at the end of the apparent statement,
852// for example:
853// DCHECK_EQ(string("abc")[1], 'b');
854//
brucedawson93a60b8c2016-04-28 20:46:16855// WARNING: These don't compile correctly if one of the arguments is a pointer
856// and the other is NULL. In new code, prefer nullptr instead. To
857// work around this for C++98, simply static_cast NULL to the type of the
858// desired pointer.
initial.commitd7cae122008-07-26 21:49:38859
860#define DCHECK_EQ(val1, val2) DCHECK_OP(EQ, ==, val1, val2)
861#define DCHECK_NE(val1, val2) DCHECK_OP(NE, !=, val1, val2)
862#define DCHECK_LE(val1, val2) DCHECK_OP(LE, <=, val1, val2)
863#define DCHECK_LT(val1, val2) DCHECK_OP(LT, < , val1, val2)
864#define DCHECK_GE(val1, val2) DCHECK_OP(GE, >=, val1, val2)
865#define DCHECK_GT(val1, val2) DCHECK_OP(GT, > , val1, val2)
866
Xiaohan Wangee536b212019-05-07 16:16:07867#if BUILDFLAG(ENABLE_LOG_ERROR_NOT_REACHED)
tnagelff3f34a2015-05-24 12:59:14868// Implement logging of NOTREACHED() as a dedicated function to get function
869// call overhead down to a minimum.
870void LogErrorNotReached(const char* file, int line);
871#define NOTREACHED() \
872 true ? ::logging::LogErrorNotReached(__FILE__, __LINE__) \
873 : EAT_STREAM_PARAMETERS
[email protected]7c67fbe2013-09-26 07:55:21874#else
initial.commitd7cae122008-07-26 21:49:38875#define NOTREACHED() DCHECK(false)
[email protected]7c67fbe2013-09-26 07:55:21876#endif
initial.commitd7cae122008-07-26 21:49:38877
878// Redefine the standard assert to use our nice log files
879#undef assert
880#define assert(x) DLOG_ASSERT(x)
881
882// This class more or less represents a particular log message. You
883// create an instance of LogMessage and then stream stuff to it.
884// When you finish streaming to it, ~LogMessage is called and the
885// full message gets streamed to the appropriate destination.
886//
887// You shouldn't actually use LogMessage's constructor to log things,
888// though. You should use the LOG() macro (and variants thereof)
889// above.
[email protected]0bea7252011-08-05 15:34:00890class BASE_EXPORT LogMessage {
initial.commitd7cae122008-07-26 21:49:38891 public:
[email protected]bf8ddf13a2014-06-18 15:02:22892 // Used for LOG(severity).
initial.commitd7cae122008-07-26 21:49:38893 LogMessage(const char* file, int line, LogSeverity severity);
894
tnagel4a045d3f2015-07-12 14:19:28895 // Used for CHECK(). Implied severity = LOG_FATAL.
896 LogMessage(const char* file, int line, const char* condition);
897
[email protected]bf8ddf13a2014-06-18 15:02:22898 // Used for CHECK_EQ(), etc. Takes ownership of the given string.
899 // Implied severity = LOG_FATAL.
[email protected]9c7132e2011-02-08 07:39:08900 LogMessage(const char* file, int line, std::string* result);
initial.commitd7cae122008-07-26 21:49:38901
[email protected]bf8ddf13a2014-06-18 15:02:22902 // Used for DCHECK_EQ(), etc. Takes ownership of the given string.
[email protected]fb62a532009-02-12 01:19:05903 LogMessage(const char* file, int line, LogSeverity severity,
[email protected]9c7132e2011-02-08 07:39:08904 std::string* result);
[email protected]fb62a532009-02-12 01:19:05905
initial.commitd7cae122008-07-26 21:49:38906 ~LogMessage();
907
908 std::ostream& stream() { return stream_; }
909
pastarmovj89f7ee12016-09-20 14:58:13910 LogSeverity severity() { return severity_; }
911 std::string str() { return stream_.str(); }
912
initial.commitd7cae122008-07-26 21:49:38913 private:
914 void Init(const char* file, int line);
915
916 LogSeverity severity_;
917 std::ostringstream stream_;
[email protected]c88873922008-07-30 13:02:03918 size_t message_start_; // Offset of the start of the message (past prefix
919 // info).
[email protected]162ac0f2010-11-04 15:50:49920 // The file and line information passed in to the constructor.
921 const char* file_;
922 const int line_;
923
[email protected]3f85caa2009-04-14 16:52:11924 // This is useful since the LogMessage class uses a lot of Win32 calls
925 // that will lose the value of GLE and the code that called the log function
926 // will have lost the thread error value when the log call returns.
Etienne Pierre-Dorayd120ebf2018-09-14 23:38:21927 base::internal::ScopedClearLastError last_error_;
initial.commitd7cae122008-07-26 21:49:38928
[email protected]39be4242008-08-07 18:31:40929 DISALLOW_COPY_AND_ASSIGN(LogMessage);
initial.commitd7cae122008-07-26 21:49:38930};
931
initial.commitd7cae122008-07-26 21:49:38932// This class is used to explicitly ignore values in the conditional
933// logging macros. This avoids compiler warnings like "value computed
934// is not used" and "statement has no effect".
[email protected]23bb71f2011-04-21 22:22:10935class LogMessageVoidify {
initial.commitd7cae122008-07-26 21:49:38936 public:
Chris Watkins091d6292017-12-13 04:25:58937 LogMessageVoidify() = default;
initial.commitd7cae122008-07-26 21:49:38938 // This has to be an operator with a precedence lower than << but
939 // higher than ?:
940 void operator&(std::ostream&) { }
941};
942
[email protected]d8617a62009-10-09 23:52:20943#if defined(OS_WIN)
944typedef unsigned long SystemErrorCode;
Fabrice de Gans-Riberi306871de2018-05-16 19:38:39945#elif defined(OS_POSIX) || defined(OS_FUCHSIA)
[email protected]d8617a62009-10-09 23:52:20946typedef int SystemErrorCode;
947#endif
948
949// Alias for ::GetLastError() on Windows and errno on POSIX. Avoids having to
950// pull in windows.h just for GetLastError() and DWORD.
[email protected]0bea7252011-08-05 15:34:00951BASE_EXPORT SystemErrorCode GetLastSystemErrorCode();
[email protected]c914d8a2014-04-23 01:11:01952BASE_EXPORT std::string SystemErrorCodeToString(SystemErrorCode error_code);
[email protected]d8617a62009-10-09 23:52:20953
954#if defined(OS_WIN)
955// Appends a formatted system message of the GetLastError() type.
[email protected]0bea7252011-08-05 15:34:00956class BASE_EXPORT Win32ErrorLogMessage {
[email protected]d8617a62009-10-09 23:52:20957 public:
958 Win32ErrorLogMessage(const char* file,
959 int line,
960 LogSeverity severity,
[email protected]d8617a62009-10-09 23:52:20961 SystemErrorCode err);
962
[email protected]d8617a62009-10-09 23:52:20963 // Appends the error message before destructing the encapsulated class.
964 ~Win32ErrorLogMessage();
965
[email protected]a502bbe72011-01-07 18:06:45966 std::ostream& stream() { return log_message_.stream(); }
967
[email protected]d8617a62009-10-09 23:52:20968 private:
969 SystemErrorCode err_;
[email protected]d8617a62009-10-09 23:52:20970 LogMessage log_message_;
971
972 DISALLOW_COPY_AND_ASSIGN(Win32ErrorLogMessage);
973};
Fabrice de Gans-Riberi306871de2018-05-16 19:38:39974#elif defined(OS_POSIX) || defined(OS_FUCHSIA)
[email protected]d8617a62009-10-09 23:52:20975// Appends a formatted system message of the errno type
[email protected]0bea7252011-08-05 15:34:00976class BASE_EXPORT ErrnoLogMessage {
[email protected]d8617a62009-10-09 23:52:20977 public:
978 ErrnoLogMessage(const char* file,
979 int line,
980 LogSeverity severity,
981 SystemErrorCode err);
982
[email protected]d8617a62009-10-09 23:52:20983 // Appends the error message before destructing the encapsulated class.
984 ~ErrnoLogMessage();
985
[email protected]a502bbe72011-01-07 18:06:45986 std::ostream& stream() { return log_message_.stream(); }
987
[email protected]d8617a62009-10-09 23:52:20988 private:
989 SystemErrorCode err_;
990 LogMessage log_message_;
991
992 DISALLOW_COPY_AND_ASSIGN(ErrnoLogMessage);
993};
994#endif // OS_WIN
995
initial.commitd7cae122008-07-26 21:49:38996// Closes the log file explicitly if open.
997// NOTE: Since the log file is opened as necessary by the action of logging
998// statements, there's no guarantee that it will stay closed
999// after this call.
[email protected]0bea7252011-08-05 15:34:001000BASE_EXPORT void CloseLogFile();
initial.commitd7cae122008-07-26 21:49:381001
Robbie McElrath8bf49842019-08-20 22:22:531002#if defined(OS_CHROMEOS)
1003// Returns a new file handle that will write to the same destination as the
1004// currently open log file. Returns nullptr if logging to a file is disabled,
1005// or if opening the file failed. This is intended to be used to initialize
1006// logging in child processes that are unable to open files.
1007BASE_EXPORT FILE* DuplicateLogFILE();
1008#endif
1009
[email protected]e36ddc82009-12-08 04:22:501010// Async signal safe logging mechanism.
[email protected]0bea7252011-08-05 15:34:001011BASE_EXPORT void RawLog(int level, const char* message);
[email protected]e36ddc82009-12-08 04:22:501012
tsniatowski612550f2016-07-21 18:26:201013#define RAW_LOG(level, message) \
1014 ::logging::RawLog(::logging::LOG_##level, message)
[email protected]e36ddc82009-12-08 04:22:501015
tsniatowski612550f2016-07-21 18:26:201016#define RAW_CHECK(condition) \
1017 do { \
kmarshall08c892f72017-02-28 03:46:181018 if (!(condition)) \
tsniatowski612550f2016-07-21 18:26:201019 ::logging::RawLog(::logging::LOG_FATAL, \
1020 "Check failed: " #condition "\n"); \
[email protected]e36ddc82009-12-08 04:22:501021 } while (0)
1022
[email protected]f01b88a2013-02-27 22:04:001023#if defined(OS_WIN)
ananta61762fb2015-09-18 01:00:091024// Returns true if logging to file is enabled.
1025BASE_EXPORT bool IsLoggingToFileEnabled();
1026
[email protected]f01b88a2013-02-27 22:04:001027// Returns the default log file path.
jdoerrie5c4dc4e2019-02-01 18:02:331028BASE_EXPORT base::string16 GetLogFileFullPath();
[email protected]f01b88a2013-02-27 22:04:001029#endif
1030
[email protected]39be4242008-08-07 18:31:401031} // namespace logging
initial.commitd7cae122008-07-26 21:49:381032
[email protected]81411c62014-07-08 23:03:061033// Note that "The behavior of a C++ program is undefined if it adds declarations
1034// or definitions to namespace std or to a namespace within namespace std unless
1035// otherwise specified." --C++11[namespace.std]
1036//
1037// We've checked that this particular definition has the intended behavior on
1038// our implementations, but it's prone to breaking in the future, and please
1039// don't imitate this in your own definitions without checking with some
1040// standard library experts.
1041namespace std {
[email protected]46ce5b562010-06-16 18:39:531042// These functions are provided as a convenience for logging, which is where we
1043// use streams (it is against Google style to use streams in other places). It
1044// is designed to allow you to emit non-ASCII Unicode strings to the log file,
1045// which is normally ASCII. It is relatively slow, so try not to use it for
1046// common cases. Non-ASCII characters will be converted to UTF-8 by these
1047// operators.
[email protected]0bea7252011-08-05 15:34:001048BASE_EXPORT std::ostream& operator<<(std::ostream& out, const wchar_t* wstr);
[email protected]46ce5b562010-06-16 18:39:531049inline std::ostream& operator<<(std::ostream& out, const std::wstring& wstr) {
1050 return out << wstr.c_str();
1051}
[email protected]81411c62014-07-08 23:03:061052} // namespace std
[email protected]46ce5b562010-06-16 18:39:531053
Daniel Bratellff541192017-11-02 14:22:281054// The NOTIMPLEMENTED() macro annotates codepaths which have not been
1055// implemented yet. If output spam is a serious concern,
1056// NOTIMPLEMENTED_LOG_ONCE can be used.
[email protected]0dfc81b2008-08-25 03:44:401057
[email protected]f6cda752008-10-30 23:54:261058#if defined(COMPILER_GCC)
1059// On Linux, with GCC, we can use __PRETTY_FUNCTION__ to get the demangled name
1060// of the current function in the NOTIMPLEMENTED message.
1061#define NOTIMPLEMENTED_MSG "Not implemented reached in " << __PRETTY_FUNCTION__
1062#else
1063#define NOTIMPLEMENTED_MSG "NOT IMPLEMENTED"
1064#endif
1065
Daniel Cheng5b0b3012019-04-26 00:58:041066#define NOTIMPLEMENTED() DLOG(ERROR) << NOTIMPLEMENTED_MSG
1067#define NOTIMPLEMENTED_LOG_ONCE() \
1068 do { \
1069 static bool logged_once = false; \
1070 DLOG_IF(ERROR, !logged_once) << NOTIMPLEMENTED_MSG; \
1071 logged_once = true; \
1072 } while (0); \
Daniel Bratellff541192017-11-02 14:22:281073 EAT_STREAM_PARAMETERS
[email protected]0dfc81b2008-08-25 03:44:401074
[email protected]39be4242008-08-07 18:31:401075#endif // BASE_LOGGING_H_