logging.h 28 KB

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