logging.h 32 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796
  1. // Copyright (c) 2012 The Chromium Authors. All rights reserved.
  2. // Use of this source code is governed by a BSD-style license that can be
  3. // found in the LICENSE file.
  4. #ifndef BASE_LOGGING_H_
  5. #define BASE_LOGGING_H_
  6. #include <stddef.h>
  7. #include <cassert>
  8. #include <cstdint>
  9. #include <sstream>
  10. #include <string>
  11. #include "base/base_export.h"
  12. #include "base/callback_forward.h"
  13. #include "base/compiler_specific.h"
  14. #include "base/dcheck_is_on.h"
  15. #include "base/logging_buildflags.h"
  16. #include "base/scoped_clear_last_error.h"
  17. #include "base/strings/string_piece_forward.h"
  18. #include "build/build_config.h"
  19. #include "build/chromeos_buildflags.h"
  20. #if BUILDFLAG(IS_CHROMEOS)
  21. #include <cstdio>
  22. #endif
  23. //
  24. // Optional message capabilities
  25. // -----------------------------
  26. // Assertion failed messages and fatal errors are displayed in a dialog box
  27. // before the application exits. However, running this UI creates a message
  28. // loop, which causes application messages to be processed and potentially
  29. // dispatched to existing application windows. Since the application is in a
  30. // bad state when this assertion dialog is displayed, these messages may not
  31. // get processed and hang the dialog, or the application might go crazy.
  32. //
  33. // Therefore, it can be beneficial to display the error dialog in a separate
  34. // process from the main application. When the logging system needs to display
  35. // a fatal error dialog box, it will look for a program called
  36. // "DebugMessage.exe" in the same directory as the application executable. It
  37. // will run this application with the message as the command line, and will
  38. // not include the name of the application as is traditional for easier
  39. // parsing.
  40. //
  41. // The code for DebugMessage.exe is only one line. In WinMain, do:
  42. // MessageBox(NULL, GetCommandLineW(), L"Fatal Error", 0);
  43. //
  44. // If DebugMessage.exe is not found, the logging code will use a normal
  45. // MessageBox, potentially causing the problems discussed above.
  46. // Instructions
  47. // ------------
  48. //
  49. // Make a bunch of macros for logging. The way to log things is to stream
  50. // things to LOG(<a particular severity level>). E.g.,
  51. //
  52. // LOG(INFO) << "Found " << num_cookies << " cookies";
  53. //
  54. // You can also do conditional logging:
  55. //
  56. // LOG_IF(INFO, num_cookies > 10) << "Got lots of cookies";
  57. //
  58. // The CHECK(condition) macro is active in both debug and release builds and
  59. // effectively performs a LOG(FATAL) which terminates the process and
  60. // generates a crashdump unless a debugger is attached.
  61. //
  62. // There are also "debug mode" logging macros like the ones above:
  63. //
  64. // DLOG(INFO) << "Found cookies";
  65. //
  66. // DLOG_IF(INFO, num_cookies > 10) << "Got lots of cookies";
  67. //
  68. // All "debug mode" logging is compiled away to nothing for non-debug mode
  69. // compiles. LOG_IF and development flags also work well together
  70. // because the code can be compiled away sometimes.
  71. //
  72. // We also have
  73. //
  74. // LOG_ASSERT(assertion);
  75. // DLOG_ASSERT(assertion);
  76. //
  77. // which is syntactic sugar for {,D}LOG_IF(FATAL, assert fails) << assertion;
  78. //
  79. // There are "verbose level" logging macros. They look like
  80. //
  81. // VLOG(1) << "I'm printed when you run the program with --v=1 or more";
  82. // VLOG(2) << "I'm printed when you run the program with --v=2 or more";
  83. //
  84. // These always log at the INFO log level (when they log at all).
  85. //
  86. // There is a build flag USE_RUNTIME_VLOG that controls whether verbose
  87. // logging is processed at runtime or at build time.
  88. //
  89. // When USE_RUNTIME_VLOG is not set, the verbose logging is processed at
  90. // build time. VLOG(n) is only included and compiled when `n` is less than or
  91. // equal to the verbose level defined by ENABLED_VLOG_LEVEL macro. Command line
  92. // switch --v and --vmodule are ignored in this mode.
  93. //
  94. // When USE_RUNTIME_VLOG is set, the verbose logging is controlled at
  95. // runtime and can be turned on module-by-module. For instance,
  96. // --vmodule=profile=2,icon_loader=1,browser_*=3,*/chromeos/*=4 --v=0
  97. // will cause:
  98. // a. VLOG(2) and lower messages to be printed from profile.{h,cc}
  99. // b. VLOG(1) and lower messages to be printed from icon_loader.{h,cc}
  100. // c. VLOG(3) and lower messages to be printed from files prefixed with
  101. // "browser"
  102. // d. VLOG(4) and lower messages to be printed from files under a
  103. // "chromeos" directory.
  104. // e. VLOG(0) and lower messages to be printed from elsewhere
  105. //
  106. // The wildcarding functionality shown by (c) supports both '*' (match
  107. // 0 or more characters) and '?' (match any single character)
  108. // wildcards. Any pattern containing a forward or backward slash will
  109. // be tested against the whole pathname and not just the module.
  110. // E.g., "*/foo/bar/*=2" would change the logging level for all code
  111. // in source files under a "foo/bar" directory.
  112. //
  113. // Note that for a Chromium binary built in release mode (is_debug = false) you
  114. // must pass "--enable-logging=stderr" in order to see the output of VLOG
  115. // statements.
  116. //
  117. // There's also VLOG_IS_ON(n) "verbose level" condition macro. To be used as
  118. //
  119. // if (VLOG_IS_ON(2)) {
  120. // // do some logging preparation and logging
  121. // // that can't be accomplished with just VLOG(2) << ...;
  122. // }
  123. //
  124. // There is also a VLOG_IF "verbose level" condition macro for sample
  125. // cases, when some extra computation and preparation for logs is not
  126. // needed.
  127. //
  128. // VLOG_IF(1, (size > 1024))
  129. // << "I'm printed when size is more than 1024 and when you run the "
  130. // "program with --v=1 or more";
  131. //
  132. // We also override the standard 'assert' to use 'DLOG_ASSERT'.
  133. //
  134. // Lastly, there is:
  135. //
  136. // PLOG(ERROR) << "Couldn't do foo";
  137. // DPLOG(ERROR) << "Couldn't do foo";
  138. // PLOG_IF(ERROR, cond) << "Couldn't do foo";
  139. // DPLOG_IF(ERROR, cond) << "Couldn't do foo";
  140. // PCHECK(condition) << "Couldn't do foo";
  141. // DPCHECK(condition) << "Couldn't do foo";
  142. //
  143. // which append the last system error to the message in string form (taken from
  144. // GetLastError() on Windows and errno on POSIX).
  145. //
  146. // The supported severity levels for macros that allow you to specify one
  147. // are (in increasing order of severity) INFO, WARNING, ERROR, and FATAL.
  148. //
  149. // Very important: logging a message at the FATAL severity level causes
  150. // the program to terminate (after the message is logged).
  151. //
  152. // There is the special severity of DFATAL, which logs FATAL in DCHECK-enabled
  153. // builds, ERROR in normal mode.
  154. //
  155. // Output is formatted as per the following example, except on Chrome OS.
  156. // [3816:3877:0812/234555.406952:VERBOSE1:drm_device_handle.cc(90)] Succeeded
  157. // authenticating /dev/dri/card0 in 0 ms with 1 attempt(s)
  158. //
  159. // The colon separated fields inside the brackets are as follows:
  160. // 0. An optional Logfile prefix (not included in this example)
  161. // 1. Process ID
  162. // 2. Thread ID
  163. // 3. The date/time of the log message, in MMDD/HHMMSS.Milliseconds format
  164. // 4. The log level
  165. // 5. The filename and line number where the log was instantiated
  166. //
  167. // Output for Chrome OS can be switched to syslog-like format. See
  168. // InitWithSyslogPrefix() in logging_chromeos.cc for details.
  169. //
  170. // Note that the visibility can be changed by setting preferences in
  171. // SetLogItems()
  172. //
  173. // Additional logging-related information can be found here:
  174. // https://chromium.googlesource.com/chromium/src/+/main/docs/linux/debugging.md#Logging
  175. namespace logging {
  176. // TODO(avi): do we want to do a unification of character types here?
  177. #if BUILDFLAG(IS_WIN)
  178. typedef wchar_t PathChar;
  179. #elif BUILDFLAG(IS_POSIX) || BUILDFLAG(IS_FUCHSIA)
  180. typedef char PathChar;
  181. #endif
  182. // A bitmask of potential logging destinations.
  183. using LoggingDestination = uint32_t;
  184. // Specifies where logs will be written. Multiple destinations can be specified
  185. // with bitwise OR.
  186. // Unless destination is LOG_NONE, all logs with severity ERROR and above will
  187. // be written to stderr in addition to the specified destination.
  188. enum : uint32_t {
  189. LOG_NONE = 0,
  190. LOG_TO_FILE = 1 << 0,
  191. LOG_TO_SYSTEM_DEBUG_LOG = 1 << 1,
  192. LOG_TO_STDERR = 1 << 2,
  193. LOG_TO_ALL = LOG_TO_FILE | LOG_TO_SYSTEM_DEBUG_LOG | LOG_TO_STDERR,
  194. // On Windows, use a file next to the exe.
  195. // On POSIX platforms, where it may not even be possible to locate the
  196. // executable on disk, use stderr.
  197. // On Fuchsia, use the Fuchsia logging service.
  198. #if BUILDFLAG(IS_FUCHSIA) || BUILDFLAG(IS_NACL)
  199. LOG_DEFAULT = LOG_TO_SYSTEM_DEBUG_LOG,
  200. #elif BUILDFLAG(IS_WIN)
  201. LOG_DEFAULT = LOG_TO_FILE,
  202. #elif BUILDFLAG(IS_POSIX)
  203. LOG_DEFAULT = LOG_TO_SYSTEM_DEBUG_LOG | LOG_TO_STDERR,
  204. #endif
  205. };
  206. // Indicates that the log file should be locked when being written to.
  207. // Unless there is only one single-threaded process that is logging to
  208. // the log file, the file should be locked during writes to make each
  209. // log output atomic. Other writers will block.
  210. //
  211. // All processes writing to the log file must have their locking set for it to
  212. // work properly. Defaults to LOCK_LOG_FILE.
  213. enum LogLockingState { LOCK_LOG_FILE, DONT_LOCK_LOG_FILE };
  214. // On startup, should we delete or append to an existing log file (if any)?
  215. // Defaults to APPEND_TO_OLD_LOG_FILE.
  216. enum OldFileDeletionState { DELETE_OLD_LOG_FILE, APPEND_TO_OLD_LOG_FILE };
  217. #if BUILDFLAG(IS_CHROMEOS)
  218. // Defines the log message prefix format to use.
  219. // LOG_FORMAT_SYSLOG indicates syslog-like message prefixes.
  220. // LOG_FORMAT_CHROME indicates the normal Chrome format.
  221. enum class BASE_EXPORT LogFormat { LOG_FORMAT_CHROME, LOG_FORMAT_SYSLOG };
  222. #endif
  223. struct BASE_EXPORT LoggingSettings {
  224. // Equivalent to logging destination enum, but allows for multiple
  225. // destinations.
  226. uint32_t logging_dest = LOG_DEFAULT;
  227. // The four settings below have an effect only when LOG_TO_FILE is
  228. // set in |logging_dest|.
  229. const PathChar* log_file_path = nullptr;
  230. LogLockingState lock_log = LOCK_LOG_FILE;
  231. OldFileDeletionState delete_old = APPEND_TO_OLD_LOG_FILE;
  232. #if BUILDFLAG(IS_CHROMEOS)
  233. // Contains an optional file that logs should be written to. If present,
  234. // |log_file_path| will be ignored, and the logging system will take ownership
  235. // of the FILE. If there's an error writing to this file, no fallback paths
  236. // will be opened.
  237. FILE* log_file = nullptr;
  238. // ChromeOS uses the syslog log format by default.
  239. LogFormat log_format = LogFormat::LOG_FORMAT_SYSLOG;
  240. #endif
  241. };
  242. // Define different names for the BaseInitLoggingImpl() function depending on
  243. // whether NDEBUG is defined or not so that we'll fail to link if someone tries
  244. // to compile logging.cc with NDEBUG but includes logging.h without defining it,
  245. // or vice versa.
  246. #if defined(NDEBUG)
  247. #define BaseInitLoggingImpl BaseInitLoggingImpl_built_with_NDEBUG
  248. #else
  249. #define BaseInitLoggingImpl BaseInitLoggingImpl_built_without_NDEBUG
  250. #endif
  251. // Implementation of the InitLogging() method declared below. We use a
  252. // more-specific name so we can #define it above without affecting other code
  253. // that has named stuff "InitLogging".
  254. BASE_EXPORT bool BaseInitLoggingImpl(const LoggingSettings& settings);
  255. // Sets the log file name and other global logging state. Calling this function
  256. // is recommended, and is normally done at the beginning of application init.
  257. // If you don't call it, all the flags will be initialized to their default
  258. // values, and there is a race condition that may leak a critical section
  259. // object if two threads try to do the first log at the same time.
  260. // See the definition of the enums above for descriptions and default values.
  261. //
  262. // The default log file is initialized to "debug.log" in the application
  263. // directory. You probably don't want this, especially since the program
  264. // directory may not be writable on an enduser's system.
  265. //
  266. // This function may be called a second time to re-direct logging (e.g after
  267. // loging in to a user partition), however it should never be called more than
  268. // twice.
  269. inline bool InitLogging(const LoggingSettings& settings) {
  270. return BaseInitLoggingImpl(settings);
  271. }
  272. // Sets the log level. Anything at or above this level will be written to the
  273. // log file/displayed to the user (if applicable). Anything below this level
  274. // will be silently ignored. The log level defaults to 0 (everything is logged
  275. // up to level INFO) if this function is not called.
  276. // Note that log messages for VLOG(x) are logged at level -x, so setting
  277. // the min log level to negative values enables verbose logging and conversely,
  278. // setting the VLOG default level will set this min level to a negative number,
  279. // effectively enabling all levels of logging.
  280. BASE_EXPORT void SetMinLogLevel(int level);
  281. // Gets the current log level.
  282. BASE_EXPORT int GetMinLogLevel();
  283. // Used by LOG_IS_ON to lazy-evaluate stream arguments.
  284. BASE_EXPORT bool ShouldCreateLogMessage(int severity);
  285. // Gets the VLOG default verbosity level.
  286. BASE_EXPORT int GetVlogVerbosity();
  287. // Note that |N| is the size *with* the null terminator.
  288. BASE_EXPORT int GetVlogLevelHelper(const char* file_start, size_t N);
  289. // Gets the current vlog level for the given file (usually taken from __FILE__).
  290. template <size_t N>
  291. int GetVlogLevel(const char (&file)[N]) {
  292. return GetVlogLevelHelper(file, N);
  293. }
  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.
  298. BASE_EXPORT void SetLogItems(bool enable_process_id, bool enable_thread_id,
  299. bool enable_timestamp, bool enable_tickcount);
  300. // Sets an optional prefix to add to each log message. |prefix| is not copied
  301. // and should be a raw string constant. |prefix| must only contain ASCII letters
  302. // to avoid confusion with PIDs and timestamps. Pass null to remove the prefix.
  303. // Logging defaults to no prefix.
  304. BASE_EXPORT void SetLogPrefix(const char* prefix);
  305. // Sets whether or not you'd like to see fatal debug messages popped up in
  306. // a dialog box or not.
  307. // Dialogs are not shown by default.
  308. BASE_EXPORT void SetShowErrorDialogs(bool enable_dialogs);
  309. // Sets the Log Assert Handler that will be used to notify of check failures.
  310. // Resets Log Assert Handler on object destruction.
  311. // The default handler shows a dialog box and then terminate the process,
  312. // however clients can use this function to override with their own handling
  313. // (e.g. a silent one for Unit Tests)
  314. using LogAssertHandlerFunction =
  315. base::RepeatingCallback<void(const char* file,
  316. int line,
  317. const base::StringPiece message,
  318. const base::StringPiece stack_trace)>;
  319. class BASE_EXPORT ScopedLogAssertHandler {
  320. public:
  321. explicit ScopedLogAssertHandler(LogAssertHandlerFunction handler);
  322. ScopedLogAssertHandler(const ScopedLogAssertHandler&) = delete;
  323. ScopedLogAssertHandler& operator=(const ScopedLogAssertHandler&) = delete;
  324. ~ScopedLogAssertHandler();
  325. };
  326. // Sets the Log Message Handler that gets passed every log message before
  327. // it's sent to other log destinations (if any).
  328. // Returns true to signal that it handled the message and the message
  329. // should not be sent to other log destinations.
  330. typedef bool (*LogMessageHandlerFunction)(int severity,
  331. const char* file, int line, size_t message_start, const std::string& str);
  332. BASE_EXPORT void SetLogMessageHandler(LogMessageHandlerFunction handler);
  333. BASE_EXPORT LogMessageHandlerFunction GetLogMessageHandler();
  334. using LogSeverity = int;
  335. constexpr LogSeverity LOGGING_VERBOSE = -1; // This is level 1 verbosity
  336. // Note: the log severities are used to index into the array of names,
  337. // see log_severity_names.
  338. constexpr LogSeverity LOGGING_INFO = 0;
  339. constexpr LogSeverity LOGGING_WARNING = 1;
  340. constexpr LogSeverity LOGGING_ERROR = 2;
  341. constexpr LogSeverity LOGGING_FATAL = 3;
  342. constexpr LogSeverity LOGGING_NUM_SEVERITIES = 4;
  343. // LOGGING_DFATAL is LOGGING_FATAL in DCHECK-enabled builds, ERROR in normal
  344. // mode.
  345. #if DCHECK_IS_ON()
  346. constexpr LogSeverity LOGGING_DFATAL = LOGGING_FATAL;
  347. #else
  348. constexpr LogSeverity LOGGING_DFATAL = LOGGING_ERROR;
  349. #endif
  350. // This block duplicates the above entries to facilitate incremental conversion
  351. // from LOG_FOO to LOGGING_FOO.
  352. // TODO(thestig): Convert existing users to LOGGING_FOO and remove this block.
  353. constexpr LogSeverity LOG_VERBOSE = LOGGING_VERBOSE;
  354. constexpr LogSeverity LOG_INFO = LOGGING_INFO;
  355. constexpr LogSeverity LOG_WARNING = LOGGING_WARNING;
  356. constexpr LogSeverity LOG_ERROR = LOGGING_ERROR;
  357. constexpr LogSeverity LOG_FATAL = LOGGING_FATAL;
  358. constexpr LogSeverity LOG_DFATAL = LOGGING_DFATAL;
  359. // A few definitions of macros that don't generate much code. These are used
  360. // by LOG() and LOG_IF, etc. Since these are used all over our code, it's
  361. // better to have compact code for these operations.
  362. #define COMPACT_GOOGLE_LOG_EX_INFO(ClassName, ...) \
  363. ::logging::ClassName(__FILE__, __LINE__, ::logging::LOGGING_INFO, \
  364. ##__VA_ARGS__)
  365. #define COMPACT_GOOGLE_LOG_EX_WARNING(ClassName, ...) \
  366. ::logging::ClassName(__FILE__, __LINE__, ::logging::LOGGING_WARNING, \
  367. ##__VA_ARGS__)
  368. #define COMPACT_GOOGLE_LOG_EX_ERROR(ClassName, ...) \
  369. ::logging::ClassName(__FILE__, __LINE__, ::logging::LOGGING_ERROR, \
  370. ##__VA_ARGS__)
  371. #define COMPACT_GOOGLE_LOG_EX_FATAL(ClassName, ...) \
  372. ::logging::ClassName(__FILE__, __LINE__, ::logging::LOGGING_FATAL, \
  373. ##__VA_ARGS__)
  374. #define COMPACT_GOOGLE_LOG_EX_DFATAL(ClassName, ...) \
  375. ::logging::ClassName(__FILE__, __LINE__, ::logging::LOGGING_DFATAL, \
  376. ##__VA_ARGS__)
  377. #define COMPACT_GOOGLE_LOG_EX_DCHECK(ClassName, ...) \
  378. ::logging::ClassName(__FILE__, __LINE__, ::logging::LOGGING_DCHECK, \
  379. ##__VA_ARGS__)
  380. #define COMPACT_GOOGLE_LOG_INFO COMPACT_GOOGLE_LOG_EX_INFO(LogMessage)
  381. #define COMPACT_GOOGLE_LOG_WARNING COMPACT_GOOGLE_LOG_EX_WARNING(LogMessage)
  382. #define COMPACT_GOOGLE_LOG_ERROR COMPACT_GOOGLE_LOG_EX_ERROR(LogMessage)
  383. #define COMPACT_GOOGLE_LOG_FATAL COMPACT_GOOGLE_LOG_EX_FATAL(LogMessage)
  384. #define COMPACT_GOOGLE_LOG_DFATAL COMPACT_GOOGLE_LOG_EX_DFATAL(LogMessage)
  385. #define COMPACT_GOOGLE_LOG_DCHECK COMPACT_GOOGLE_LOG_EX_DCHECK(LogMessage)
  386. #if BUILDFLAG(IS_WIN)
  387. // wingdi.h defines ERROR to be 0. When we call LOG(ERROR), it gets
  388. // substituted with 0, and it expands to COMPACT_GOOGLE_LOG_0. To allow us
  389. // to keep using this syntax, we define this macro to do the same thing
  390. // as COMPACT_GOOGLE_LOG_ERROR, and also define ERROR the same way that
  391. // the Windows SDK does for consistency.
  392. #define ERROR 0
  393. #define COMPACT_GOOGLE_LOG_EX_0(ClassName, ...) \
  394. COMPACT_GOOGLE_LOG_EX_ERROR(ClassName , ##__VA_ARGS__)
  395. #define COMPACT_GOOGLE_LOG_0 COMPACT_GOOGLE_LOG_ERROR
  396. // Needed for LOG_IS_ON(ERROR).
  397. constexpr LogSeverity LOGGING_0 = LOGGING_ERROR;
  398. #endif
  399. // As special cases, we can assume that LOG_IS_ON(FATAL) always holds. Also,
  400. // LOG_IS_ON(DFATAL) always holds in debug mode. In particular, CHECK()s will
  401. // always fire if they fail.
  402. #define LOG_IS_ON(severity) \
  403. (::logging::ShouldCreateLogMessage(::logging::LOGGING_##severity))
  404. #if !BUILDFLAG(USE_RUNTIME_VLOG)
  405. // When USE_RUNTIME_VLOG is not set, --vmodule is completely ignored and
  406. // ENABLED_VLOG_LEVEL macro is used to determine the enabled VLOG levels
  407. // at build time.
  408. //
  409. // Files that need VLOG would need to redefine ENABLED_VLOG_LEVEL to a desired
  410. // VLOG level number,
  411. // e.g.
  412. // To enable VLOG(1) output,
  413. //
  414. // For a source cc file:
  415. //
  416. // #undef ENABLED_VLOG_LEVEL
  417. // #define ENABLED_VLOG_LEVEL 1
  418. //
  419. // For all cc files in a build target of a BUILD.gn:
  420. //
  421. // source_set("build_target") {
  422. // ...
  423. //
  424. // defines = ["ENABLED_VLOG_LEVEL=1"]
  425. // }
  426. // Returns a vlog level that suppresses all vlogs. Using this function so that
  427. // compiler cannot calculate VLOG_IS_ON() and generate unreached code
  428. // warnings.
  429. BASE_EXPORT int GetDisableAllVLogLevel();
  430. // Define the default ENABLED_VLOG_LEVEL if it is not defined. This is to
  431. // allow ENABLED_VLOG_LEVEL to be overridden from defines in cc flags.
  432. #if !defined(ENABLED_VLOG_LEVEL)
  433. #define ENABLED_VLOG_LEVEL (logging::GetDisableAllVLogLevel())
  434. #endif // !defined(ENABLED_VLOG_LEVEL)
  435. #define VLOG_IS_ON(verboselevel) ((verboselevel) <= (ENABLED_VLOG_LEVEL))
  436. #else // !BUILDFLAG(USE_RUNTIME_VLOG)
  437. // We don't do any caching tricks with VLOG_IS_ON() like the
  438. // google-glog version since it increases binary size. This means
  439. // that using the v-logging functions in conjunction with --vmodule
  440. // may be slow.
  441. #define VLOG_IS_ON(verboselevel) \
  442. ((verboselevel) <= ::logging::GetVlogLevel(__FILE__))
  443. #endif // !BUILDFLAG(USE_RUNTIME_VLOG)
  444. // Helper macro which avoids evaluating the arguments to a stream if
  445. // the condition doesn't hold. Condition is evaluated once and only once.
  446. #define LAZY_STREAM(stream, condition) \
  447. !(condition) ? (void) 0 : ::logging::LogMessageVoidify() & (stream)
  448. // We use the preprocessor's merging operator, "##", so that, e.g.,
  449. // LOG(INFO) becomes the token COMPACT_GOOGLE_LOG_INFO. There's some funny
  450. // subtle difference between ostream member streaming functions (e.g.,
  451. // ostream::operator<<(int) and ostream non-member streaming functions
  452. // (e.g., ::operator<<(ostream&, string&): it turns out that it's
  453. // impossible to stream something like a string directly to an unnamed
  454. // ostream. We employ a neat hack by calling the stream() member
  455. // function of LogMessage which seems to avoid the problem.
  456. #define LOG_STREAM(severity) COMPACT_GOOGLE_LOG_ ## severity.stream()
  457. #define LOG(severity) LAZY_STREAM(LOG_STREAM(severity), LOG_IS_ON(severity))
  458. #define LOG_IF(severity, condition) \
  459. LAZY_STREAM(LOG_STREAM(severity), LOG_IS_ON(severity) && (condition))
  460. // The VLOG macros log with negative verbosities.
  461. #define VLOG_STREAM(verbose_level) \
  462. ::logging::LogMessage(__FILE__, __LINE__, -(verbose_level)).stream()
  463. #define VLOG(verbose_level) \
  464. LAZY_STREAM(VLOG_STREAM(verbose_level), VLOG_IS_ON(verbose_level))
  465. #define VLOG_IF(verbose_level, condition) \
  466. LAZY_STREAM(VLOG_STREAM(verbose_level), \
  467. VLOG_IS_ON(verbose_level) && (condition))
  468. #if defined (OS_WIN)
  469. #define VPLOG_STREAM(verbose_level) \
  470. ::logging::Win32ErrorLogMessage(__FILE__, __LINE__, -(verbose_level), \
  471. ::logging::GetLastSystemErrorCode()).stream()
  472. #elif BUILDFLAG(IS_POSIX) || BUILDFLAG(IS_FUCHSIA)
  473. #define VPLOG_STREAM(verbose_level) \
  474. ::logging::ErrnoLogMessage(__FILE__, __LINE__, -(verbose_level), \
  475. ::logging::GetLastSystemErrorCode()).stream()
  476. #endif
  477. #define VPLOG(verbose_level) \
  478. LAZY_STREAM(VPLOG_STREAM(verbose_level), VLOG_IS_ON(verbose_level))
  479. #define VPLOG_IF(verbose_level, condition) \
  480. LAZY_STREAM(VPLOG_STREAM(verbose_level), \
  481. VLOG_IS_ON(verbose_level) && (condition))
  482. // TODO(akalin): Add more VLOG variants, e.g. VPLOG.
  483. #define LOG_ASSERT(condition) \
  484. LOG_IF(FATAL, !(ANALYZER_ASSUME_TRUE(condition))) \
  485. << "Assert failed: " #condition ". "
  486. #if BUILDFLAG(IS_WIN)
  487. #define PLOG_STREAM(severity) \
  488. COMPACT_GOOGLE_LOG_EX_ ## severity(Win32ErrorLogMessage, \
  489. ::logging::GetLastSystemErrorCode()).stream()
  490. #elif BUILDFLAG(IS_POSIX) || BUILDFLAG(IS_FUCHSIA)
  491. #define PLOG_STREAM(severity) \
  492. COMPACT_GOOGLE_LOG_EX_ ## severity(ErrnoLogMessage, \
  493. ::logging::GetLastSystemErrorCode()).stream()
  494. #endif
  495. #define PLOG(severity) \
  496. LAZY_STREAM(PLOG_STREAM(severity), LOG_IS_ON(severity))
  497. #define PLOG_IF(severity, condition) \
  498. LAZY_STREAM(PLOG_STREAM(severity), LOG_IS_ON(severity) && (condition))
  499. BASE_EXPORT extern std::ostream* g_swallow_stream;
  500. // Note that g_swallow_stream is used instead of an arbitrary LOG() stream to
  501. // avoid the creation of an object with a non-trivial destructor (LogMessage).
  502. // On MSVC x86 (checked on 2015 Update 3), this causes a few additional
  503. // pointless instructions to be emitted even at full optimization level, even
  504. // though the : arm of the ternary operator is clearly never executed. Using a
  505. // simpler object to be &'d with Voidify() avoids these extra instructions.
  506. // Using a simpler POD object with a templated operator<< also works to avoid
  507. // these instructions. However, this causes warnings on statically defined
  508. // implementations of operator<<(std::ostream, ...) in some .cc files, because
  509. // they become defined-but-unreferenced functions. A reinterpret_cast of 0 to an
  510. // ostream* also is not suitable, because some compilers warn of undefined
  511. // behavior.
  512. #define EAT_STREAM_PARAMETERS \
  513. true ? (void)0 \
  514. : ::logging::LogMessageVoidify() & (*::logging::g_swallow_stream)
  515. // Definitions for DLOG et al.
  516. #if DCHECK_IS_ON()
  517. #define DLOG_IS_ON(severity) LOG_IS_ON(severity)
  518. #define DLOG_IF(severity, condition) LOG_IF(severity, condition)
  519. #define DLOG_ASSERT(condition) LOG_ASSERT(condition)
  520. #define DPLOG_IF(severity, condition) PLOG_IF(severity, condition)
  521. #define DVLOG_IF(verboselevel, condition) VLOG_IF(verboselevel, condition)
  522. #define DVPLOG_IF(verboselevel, condition) VPLOG_IF(verboselevel, condition)
  523. #else // DCHECK_IS_ON()
  524. // If !DCHECK_IS_ON(), we want to avoid emitting any references to |condition|
  525. // (which may reference a variable defined only if DCHECK_IS_ON()).
  526. // Contrast this with DCHECK et al., which has different behavior.
  527. #define DLOG_IS_ON(severity) false
  528. #define DLOG_IF(severity, condition) EAT_STREAM_PARAMETERS
  529. #define DLOG_ASSERT(condition) EAT_STREAM_PARAMETERS
  530. #define DPLOG_IF(severity, condition) EAT_STREAM_PARAMETERS
  531. #define DVLOG_IF(verboselevel, condition) EAT_STREAM_PARAMETERS
  532. #define DVPLOG_IF(verboselevel, condition) EAT_STREAM_PARAMETERS
  533. #endif // DCHECK_IS_ON()
  534. #define DLOG(severity) \
  535. LAZY_STREAM(LOG_STREAM(severity), DLOG_IS_ON(severity))
  536. #define DPLOG(severity) \
  537. LAZY_STREAM(PLOG_STREAM(severity), DLOG_IS_ON(severity))
  538. #define DVLOG(verboselevel) DVLOG_IF(verboselevel, true)
  539. #define DVPLOG(verboselevel) DVPLOG_IF(verboselevel, true)
  540. // Definitions for DCHECK et al.
  541. #if BUILDFLAG(DCHECK_IS_CONFIGURABLE)
  542. BASE_EXPORT extern LogSeverity LOGGING_DCHECK;
  543. #else
  544. constexpr LogSeverity LOGGING_DCHECK = LOGGING_FATAL;
  545. #endif // BUILDFLAG(DCHECK_IS_CONFIGURABLE)
  546. // Redefine the standard assert to use our nice log files
  547. #undef assert
  548. #define assert(x) DLOG_ASSERT(x)
  549. // This class more or less represents a particular log message. You
  550. // create an instance of LogMessage and then stream stuff to it.
  551. // When you finish streaming to it, ~LogMessage is called and the
  552. // full message gets streamed to the appropriate destination.
  553. //
  554. // You shouldn't actually use LogMessage's constructor to log things,
  555. // though. You should use the LOG() macro (and variants thereof)
  556. // above.
  557. class BASE_EXPORT LogMessage {
  558. public:
  559. // Used for LOG(severity).
  560. LogMessage(const char* file, int line, LogSeverity severity);
  561. // Used for CHECK(). Implied severity = LOGGING_FATAL.
  562. LogMessage(const char* file, int line, const char* condition);
  563. LogMessage(const LogMessage&) = delete;
  564. LogMessage& operator=(const LogMessage&) = delete;
  565. virtual ~LogMessage();
  566. std::ostream& stream() { return stream_; }
  567. LogSeverity severity() const { return severity_; }
  568. std::string str() const { return stream_.str(); }
  569. const char* file() const { return file_; }
  570. int line() const { return line_; }
  571. // Gets file:line: message in a format suitable for crash reporting.
  572. std::string BuildCrashString() const;
  573. private:
  574. void Init(const char* file, int line);
  575. const LogSeverity severity_;
  576. std::ostringstream stream_;
  577. size_t message_start_; // Offset of the start of the message (past prefix
  578. // info).
  579. // The file and line information passed in to the constructor.
  580. const char* const file_;
  581. const int line_;
  582. // This is useful since the LogMessage class uses a lot of Win32 calls
  583. // that will lose the value of GLE and the code that called the log function
  584. // will have lost the thread error value when the log call returns.
  585. base::ScopedClearLastError last_error_;
  586. #if BUILDFLAG(IS_CHROMEOS)
  587. void InitWithSyslogPrefix(base::StringPiece filename,
  588. int line,
  589. uint64_t tick_count,
  590. const char* log_severity_name_c_str,
  591. const char* log_prefix,
  592. bool enable_process_id,
  593. bool enable_thread_id,
  594. bool enable_timestamp,
  595. bool enable_tickcount);
  596. #endif
  597. };
  598. // This class is used to explicitly ignore values in the conditional
  599. // logging macros. This avoids compiler warnings like "value computed
  600. // is not used" and "statement has no effect".
  601. class LogMessageVoidify {
  602. public:
  603. LogMessageVoidify() = default;
  604. // This has to be an operator with a precedence lower than << but
  605. // higher than ?:
  606. void operator&(std::ostream&) { }
  607. };
  608. #if BUILDFLAG(IS_WIN)
  609. typedef unsigned long SystemErrorCode;
  610. #elif BUILDFLAG(IS_POSIX) || BUILDFLAG(IS_FUCHSIA)
  611. typedef int SystemErrorCode;
  612. #endif
  613. // Alias for ::GetLastError() on Windows and errno on POSIX. Avoids having to
  614. // pull in windows.h just for GetLastError() and DWORD.
  615. BASE_EXPORT SystemErrorCode GetLastSystemErrorCode();
  616. BASE_EXPORT std::string SystemErrorCodeToString(SystemErrorCode error_code);
  617. #if BUILDFLAG(IS_WIN)
  618. // Appends a formatted system message of the GetLastError() type.
  619. class BASE_EXPORT Win32ErrorLogMessage : public LogMessage {
  620. public:
  621. Win32ErrorLogMessage(const char* file,
  622. int line,
  623. LogSeverity severity,
  624. SystemErrorCode err);
  625. Win32ErrorLogMessage(const Win32ErrorLogMessage&) = delete;
  626. Win32ErrorLogMessage& operator=(const Win32ErrorLogMessage&) = delete;
  627. // Appends the error message before destructing the encapsulated class.
  628. ~Win32ErrorLogMessage() override;
  629. private:
  630. SystemErrorCode err_;
  631. };
  632. #elif BUILDFLAG(IS_POSIX) || BUILDFLAG(IS_FUCHSIA)
  633. // Appends a formatted system message of the errno type
  634. class BASE_EXPORT ErrnoLogMessage : public LogMessage {
  635. public:
  636. ErrnoLogMessage(const char* file,
  637. int line,
  638. LogSeverity severity,
  639. SystemErrorCode err);
  640. ErrnoLogMessage(const ErrnoLogMessage&) = delete;
  641. ErrnoLogMessage& operator=(const ErrnoLogMessage&) = delete;
  642. // Appends the error message before destructing the encapsulated class.
  643. ~ErrnoLogMessage() override;
  644. private:
  645. SystemErrorCode err_;
  646. };
  647. #endif // BUILDFLAG(IS_WIN)
  648. // Closes the log file explicitly if open.
  649. // NOTE: Since the log file is opened as necessary by the action of logging
  650. // statements, there's no guarantee that it will stay closed
  651. // after this call.
  652. BASE_EXPORT void CloseLogFile();
  653. #if BUILDFLAG(IS_CHROMEOS_ASH)
  654. // Returns a new file handle that will write to the same destination as the
  655. // currently open log file. Returns nullptr if logging to a file is disabled,
  656. // or if opening the file failed. This is intended to be used to initialize
  657. // logging in child processes that are unable to open files.
  658. BASE_EXPORT FILE* DuplicateLogFILE();
  659. #endif
  660. // Async signal safe logging mechanism.
  661. BASE_EXPORT void RawLog(int level, const char* message);
  662. #define RAW_LOG(level, message) \
  663. ::logging::RawLog(::logging::LOGGING_##level, message)
  664. #if BUILDFLAG(IS_WIN)
  665. // Returns true if logging to file is enabled.
  666. BASE_EXPORT bool IsLoggingToFileEnabled();
  667. // Returns the default log file path.
  668. BASE_EXPORT std::wstring GetLogFileFullPath();
  669. #endif
  670. } // namespace logging
  671. // Note that "The behavior of a C++ program is undefined if it adds declarations
  672. // or definitions to namespace std or to a namespace within namespace std unless
  673. // otherwise specified." --C++11[namespace.std]
  674. //
  675. // We've checked that this particular definition has the intended behavior on
  676. // our implementations, but it's prone to breaking in the future, and please
  677. // don't imitate this in your own definitions without checking with some
  678. // standard library experts.
  679. namespace std {
  680. // These functions are provided as a convenience for logging, which is where we
  681. // use streams (it is against Google style to use streams in other places). It
  682. // is designed to allow you to emit non-ASCII Unicode strings to the log file,
  683. // which is normally ASCII. It is relatively slow, so try not to use it for
  684. // common cases. Non-ASCII characters will be converted to UTF-8 by these
  685. // operators.
  686. BASE_EXPORT std::ostream& operator<<(std::ostream& out, const wchar_t* wstr);
  687. BASE_EXPORT std::ostream& operator<<(std::ostream& out,
  688. const std::wstring& wstr);
  689. BASE_EXPORT std::ostream& operator<<(std::ostream& out, const char16_t* str16);
  690. BASE_EXPORT std::ostream& operator<<(std::ostream& out,
  691. const std::u16string& str16);
  692. } // namespace std
  693. #endif // BASE_LOGGING_H_