logging.h 30 KB

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