PageRenderTime 65ms CodeModel.GetById 23ms RepoModel.GetById 1ms app.codeStats 0ms

/thirdparty/breakpad/third_party/glog/src/windows/glog/logging.h

http://github.com/tomahawk-player/tomahawk
C Header | 1510 lines | 692 code | 215 blank | 603 comment | 47 complexity | 5a1627ede33588857a6dbffca65f74f8 MD5 | raw file
Possible License(s): LGPL-2.1, BSD-3-Clause, GPL-3.0, GPL-2.0
  1. // This file is automatically generated from src/glog/logging.h.in
  2. // using src/windows/preprocess.sh.
  3. // DO NOT EDIT!
  4. // Copyright (c) 1999, Google Inc.
  5. // All rights reserved.
  6. //
  7. // Redistribution and use in source and binary forms, with or without
  8. // modification, are permitted provided that the following conditions are
  9. // met:
  10. //
  11. // * Redistributions of source code must retain the above copyright
  12. // notice, this list of conditions and the following disclaimer.
  13. // * Redistributions in binary form must reproduce the above
  14. // copyright notice, this list of conditions and the following disclaimer
  15. // in the documentation and/or other materials provided with the
  16. // distribution.
  17. // * Neither the name of Google Inc. nor the names of its
  18. // contributors may be used to endorse or promote products derived from
  19. // this software without specific prior written permission.
  20. //
  21. // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
  22. // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
  23. // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
  24. // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
  25. // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
  26. // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
  27. // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
  28. // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
  29. // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
  30. // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
  31. // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  32. //
  33. // Author: Ray Sidney
  34. //
  35. // This file contains #include information about logging-related stuff.
  36. // Pretty much everybody needs to #include this file so that they can
  37. // log various happenings.
  38. //
  39. #ifndef _LOGGING_H_
  40. #define _LOGGING_H_
  41. #include <errno.h>
  42. #include <string.h>
  43. #include <time.h>
  44. #include <string>
  45. #if 0
  46. # include <unistd.h>
  47. #endif
  48. #ifdef __DEPRECATED
  49. // Make GCC quiet.
  50. # undef __DEPRECATED
  51. # include <strstream>
  52. # define __DEPRECATED
  53. #else
  54. # include <strstream>
  55. #endif
  56. #include <vector>
  57. // Annoying stuff for windows -- makes sure clients can import these functions
  58. #ifndef GOOGLE_GLOG_DLL_DECL
  59. # if defined(_WIN32) && !defined(__CYGWIN__)
  60. # define GOOGLE_GLOG_DLL_DECL __declspec(dllimport)
  61. # else
  62. # define GOOGLE_GLOG_DLL_DECL
  63. # endif
  64. #endif
  65. // We care a lot about number of bits things take up. Unfortunately,
  66. // systems define their bit-specific ints in a lot of different ways.
  67. // We use our own way, and have a typedef to get there.
  68. // Note: these commands below may look like "#if 1" or "#if 0", but
  69. // that's because they were constructed that way at ./configure time.
  70. // Look at logging.h.in to see how they're calculated (based on your config).
  71. #if 0
  72. #include <stdint.h> // the normal place uint16_t is defined
  73. #endif
  74. #if 0
  75. #include <sys/types.h> // the normal place u_int16_t is defined
  76. #endif
  77. #if 0
  78. #include <inttypes.h> // a third place for uint16_t or u_int16_t
  79. #endif
  80. #if 0
  81. #include <gflags/gflags.h>
  82. #endif
  83. namespace google {
  84. #if 0 // the C99 format
  85. typedef int32_t int32;
  86. typedef uint32_t uint32;
  87. typedef int64_t int64;
  88. typedef uint64_t uint64;
  89. #elif 0 // the BSD format
  90. typedef int32_t int32;
  91. typedef u_int32_t uint32;
  92. typedef int64_t int64;
  93. typedef u_int64_t uint64;
  94. #elif 1 // the windows (vc7) format
  95. typedef __int32 int32;
  96. typedef unsigned __int32 uint32;
  97. typedef __int64 int64;
  98. typedef unsigned __int64 uint64;
  99. #else
  100. #error Do not know how to define a 32-bit integer quantity on your system
  101. #endif
  102. }
  103. // The global value of GOOGLE_STRIP_LOG. All the messages logged to
  104. // LOG(XXX) with severity less than GOOGLE_STRIP_LOG will not be displayed.
  105. // If it can be determined at compile time that the message will not be
  106. // printed, the statement will be compiled out.
  107. //
  108. // Example: to strip out all INFO and WARNING messages, use the value
  109. // of 2 below. To make an exception for WARNING messages from a single
  110. // file, add "#define GOOGLE_STRIP_LOG 1" to that file _before_ including
  111. // base/logging.h
  112. #ifndef GOOGLE_STRIP_LOG
  113. #define GOOGLE_STRIP_LOG 0
  114. #endif
  115. // GCC can be told that a certain branch is not likely to be taken (for
  116. // instance, a CHECK failure), and use that information in static analysis.
  117. // Giving it this information can help it optimize for the common case in
  118. // the absence of better information (ie. -fprofile-arcs).
  119. //
  120. #ifndef GOOGLE_PREDICT_BRANCH_NOT_TAKEN
  121. #if 0
  122. #define GOOGLE_PREDICT_BRANCH_NOT_TAKEN(x) (__builtin_expect(x, 0))
  123. #else
  124. #define GOOGLE_PREDICT_BRANCH_NOT_TAKEN(x) x
  125. #endif
  126. #endif
  127. // Make a bunch of macros for logging. The way to log things is to stream
  128. // things to LOG(<a particular severity level>). E.g.,
  129. //
  130. // LOG(INFO) << "Found " << num_cookies << " cookies";
  131. //
  132. // You can capture log messages in a string, rather than reporting them
  133. // immediately:
  134. //
  135. // vector<string> errors;
  136. // LOG_STRING(ERROR, &errors) << "Couldn't parse cookie #" << cookie_num;
  137. //
  138. // This pushes back the new error onto 'errors'; if given a NULL pointer,
  139. // it reports the error via LOG(ERROR).
  140. //
  141. // You can also do conditional logging:
  142. //
  143. // LOG_IF(INFO, num_cookies > 10) << "Got lots of cookies";
  144. //
  145. // You can also do occasional logging (log every n'th occurrence of an
  146. // event):
  147. //
  148. // LOG_EVERY_N(INFO, 10) << "Got the " << COUNTER << "th cookie";
  149. //
  150. // The above will cause log messages to be output on the 1st, 11th, 21st, ...
  151. // times it is executed. Note that the special COUNTER value is used to
  152. // identify which repetition is happening.
  153. //
  154. // You can also do occasional conditional logging (log every n'th
  155. // occurrence of an event, when condition is satisfied):
  156. //
  157. // LOG_IF_EVERY_N(INFO, (size > 1024), 10) << "Got the " << COUNTER
  158. // << "th big cookie";
  159. //
  160. // You can log messages the first N times your code executes a line. E.g.
  161. //
  162. // LOG_FIRST_N(INFO, 20) << "Got the " << COUNTER << "th cookie";
  163. //
  164. // Outputs log messages for the first 20 times it is executed.
  165. //
  166. // Analogous SYSLOG, SYSLOG_IF, and SYSLOG_EVERY_N macros are available.
  167. // These log to syslog as well as to the normal logs. If you use these at
  168. // all, you need to be aware that syslog can drastically reduce performance,
  169. // especially if it is configured for remote logging! Don't use these
  170. // unless you fully understand this and have a concrete need to use them.
  171. // Even then, try to minimize your use of them.
  172. //
  173. // There are also "debug mode" logging macros like the ones above:
  174. //
  175. // DLOG(INFO) << "Found cookies";
  176. //
  177. // DLOG_IF(INFO, num_cookies > 10) << "Got lots of cookies";
  178. //
  179. // DLOG_EVERY_N(INFO, 10) << "Got the " << COUNTER << "th cookie";
  180. //
  181. // All "debug mode" logging is compiled away to nothing for non-debug mode
  182. // compiles.
  183. //
  184. // We also have
  185. //
  186. // LOG_ASSERT(assertion);
  187. // DLOG_ASSERT(assertion);
  188. //
  189. // which is syntactic sugar for {,D}LOG_IF(FATAL, assert fails) << assertion;
  190. //
  191. // There are "verbose level" logging macros. They look like
  192. //
  193. // VLOG(1) << "I'm printed when you run the program with --v=1 or more";
  194. // VLOG(2) << "I'm printed when you run the program with --v=2 or more";
  195. //
  196. // These always log at the INFO log level (when they log at all).
  197. // The verbose logging can also be turned on module-by-module. For instance,
  198. // --vmodule=mapreduce=2,file=1,gfs*=3 --v=0
  199. // will cause:
  200. // a. VLOG(2) and lower messages to be printed from mapreduce.{h,cc}
  201. // b. VLOG(1) and lower messages to be printed from file.{h,cc}
  202. // c. VLOG(3) and lower messages to be printed from files prefixed with "gfs"
  203. // d. VLOG(0) and lower messages to be printed from elsewhere
  204. //
  205. // The wildcarding functionality shown by (c) supports both '*' (match
  206. // 0 or more characters) and '?' (match any single character) wildcards.
  207. //
  208. // There's also VLOG_IS_ON(n) "verbose level" condition macro. To be used as
  209. //
  210. // if (VLOG_IS_ON(2)) {
  211. // // do some logging preparation and logging
  212. // // that can't be accomplished with just VLOG(2) << ...;
  213. // }
  214. //
  215. // There are also VLOG_IF, VLOG_EVERY_N and VLOG_IF_EVERY_N "verbose level"
  216. // condition macros for sample cases, when some extra computation and
  217. // preparation for logs is not needed.
  218. // VLOG_IF(1, (size > 1024))
  219. // << "I'm printed when size is more than 1024 and when you run the "
  220. // "program with --v=1 or more";
  221. // VLOG_EVERY_N(1, 10)
  222. // << "I'm printed every 10th occurrence, and when you run the program "
  223. // "with --v=1 or more. Present occurence is " << COUNTER;
  224. // VLOG_IF_EVERY_N(1, (size > 1024), 10)
  225. // << "I'm printed on every 10th occurence of case when size is more "
  226. // " than 1024, when you run the program with --v=1 or more. ";
  227. // "Present occurence is " << COUNTER;
  228. //
  229. // The supported severity levels for macros that allow you to specify one
  230. // are (in increasing order of severity) INFO, WARNING, ERROR, and FATAL.
  231. // Note that messages of a given severity are logged not only in the
  232. // logfile for that severity, but also in all logfiles of lower severity.
  233. // E.g., a message of severity FATAL will be logged to the logfiles of
  234. // severity FATAL, ERROR, WARNING, and INFO.
  235. //
  236. // There is also the special severity of DFATAL, which logs FATAL in
  237. // debug mode, ERROR in normal mode.
  238. //
  239. // Very important: logging a message at the FATAL severity level causes
  240. // the program to terminate (after the message is logged).
  241. //
  242. // Unless otherwise specified, logs will be written to the filename
  243. // "<program name>.<hostname>.<user name>.log.<severity level>.", followed
  244. // by the date, time, and pid (you can't prevent the date, time, and pid
  245. // from being in the filename).
  246. //
  247. // The logging code takes two flags:
  248. // --v=# set the verbose level
  249. // --logtostderr log all the messages to stderr instead of to logfiles
  250. // LOG LINE PREFIX FORMAT
  251. //
  252. // Log lines have this form:
  253. //
  254. // Lmmdd hh:mm:ss.uuuuuu threadid file:line] msg...
  255. //
  256. // where the fields are defined as follows:
  257. //
  258. // L A single character, representing the log level
  259. // (eg 'I' for INFO)
  260. // mm The month (zero padded; ie May is '05')
  261. // dd The day (zero padded)
  262. // hh:mm:ss.uuuuuu Time in hours, minutes and fractional seconds
  263. // threadid The space-padded thread ID as returned by GetTID()
  264. // (this matches the PID on Linux)
  265. // file The file name
  266. // line The line number
  267. // msg The user-supplied message
  268. //
  269. // Example:
  270. //
  271. // I1103 11:57:31.739339 24395 google.cc:2341] Command line: ./some_prog
  272. // I1103 11:57:31.739403 24395 google.cc:2342] Process id 24395
  273. //
  274. // NOTE: although the microseconds are useful for comparing events on
  275. // a single machine, clocks on different machines may not be well
  276. // synchronized. Hence, use caution when comparing the low bits of
  277. // timestamps from different machines.
  278. #ifndef DECLARE_VARIABLE
  279. #define MUST_UNDEF_GFLAGS_DECLARE_MACROS
  280. #define DECLARE_VARIABLE(type, name, tn) \
  281. namespace FLAG__namespace_do_not_use_directly_use_DECLARE_##tn##_instead { \
  282. extern GOOGLE_GLOG_DLL_DECL type FLAGS_##name; \
  283. } \
  284. using FLAG__namespace_do_not_use_directly_use_DECLARE_##tn##_instead::FLAGS_##name
  285. // bool specialization
  286. #define DECLARE_bool(name) \
  287. DECLARE_VARIABLE(bool, name, bool)
  288. // int32 specialization
  289. #define DECLARE_int32(name) \
  290. DECLARE_VARIABLE(google::int32, name, int32)
  291. // Special case for string, because we have to specify the namespace
  292. // std::string, which doesn't play nicely with our FLAG__namespace hackery.
  293. #define DECLARE_string(name) \
  294. namespace FLAG__namespace_do_not_use_directly_use_DECLARE_string_instead { \
  295. extern GOOGLE_GLOG_DLL_DECL std::string FLAGS_##name; \
  296. } \
  297. using FLAG__namespace_do_not_use_directly_use_DECLARE_string_instead::FLAGS_##name
  298. #endif
  299. // Set whether log messages go to stderr instead of logfiles
  300. DECLARE_bool(logtostderr);
  301. // Set whether log messages go to stderr in addition to logfiles.
  302. DECLARE_bool(alsologtostderr);
  303. // Log messages at a level >= this flag are automatically sent to
  304. // stderr in addition to log files.
  305. DECLARE_int32(stderrthreshold);
  306. // Set whether the log prefix should be prepended to each line of output.
  307. DECLARE_bool(log_prefix);
  308. // Log messages at a level <= this flag are buffered.
  309. // Log messages at a higher level are flushed immediately.
  310. DECLARE_int32(logbuflevel);
  311. // Sets the maximum number of seconds which logs may be buffered for.
  312. DECLARE_int32(logbufsecs);
  313. // Log suppression level: messages logged at a lower level than this
  314. // are suppressed.
  315. DECLARE_int32(minloglevel);
  316. // If specified, logfiles are written into this directory instead of the
  317. // default logging directory.
  318. DECLARE_string(log_dir);
  319. // Sets the path of the directory into which to put additional links
  320. // to the log files.
  321. DECLARE_string(log_link);
  322. DECLARE_int32(v); // in vlog_is_on.cc
  323. // Sets the maximum log file size (in MB).
  324. DECLARE_int32(max_log_size);
  325. // Sets whether to avoid logging to the disk if the disk is full.
  326. DECLARE_bool(stop_logging_if_full_disk);
  327. #ifdef MUST_UNDEF_GFLAGS_DECLARE_MACROS
  328. #undef MUST_UNDEF_GFLAGS_DECLARE_MACROS
  329. #undef DECLARE_VARIABLE
  330. #undef DECLARE_bool
  331. #undef DECLARE_int32
  332. #undef DECLARE_string
  333. #endif
  334. // Log messages below the GOOGLE_STRIP_LOG level will be compiled away for
  335. // security reasons. See LOG(severtiy) below.
  336. // A few definitions of macros that don't generate much code. Since
  337. // LOG(INFO) and its ilk are used all over our code, it's
  338. // better to have compact code for these operations.
  339. #if GOOGLE_STRIP_LOG == 0
  340. #define COMPACT_GOOGLE_LOG_INFO google::LogMessage( \
  341. __FILE__, __LINE__)
  342. #define LOG_TO_STRING_INFO(message) google::LogMessage( \
  343. __FILE__, __LINE__, google::INFO, message)
  344. #else
  345. #define COMPACT_GOOGLE_LOG_INFO google::NullStream()
  346. #define LOG_TO_STRING_INFO(message) google::NullStream()
  347. #endif
  348. #if GOOGLE_STRIP_LOG <= 1
  349. #define COMPACT_GOOGLE_LOG_WARNING google::LogMessage( \
  350. __FILE__, __LINE__, google::WARNING)
  351. #define LOG_TO_STRING_WARNING(message) google::LogMessage( \
  352. __FILE__, __LINE__, google::WARNING, message)
  353. #else
  354. #define COMPACT_GOOGLE_LOG_WARNING google::NullStream()
  355. #define LOG_TO_STRING_WARNING(message) google::NullStream()
  356. #endif
  357. #if GOOGLE_STRIP_LOG <= 2
  358. #define COMPACT_GOOGLE_LOG_ERROR google::LogMessage( \
  359. __FILE__, __LINE__, google::ERROR)
  360. #define LOG_TO_STRING_ERROR(message) google::LogMessage( \
  361. __FILE__, __LINE__, google::ERROR, message)
  362. #else
  363. #define COMPACT_GOOGLE_LOG_ERROR google::NullStream()
  364. #define LOG_TO_STRING_ERROR(message) google::NullStream()
  365. #endif
  366. #if GOOGLE_STRIP_LOG <= 3
  367. #define COMPACT_GOOGLE_LOG_FATAL google::LogMessageFatal( \
  368. __FILE__, __LINE__)
  369. #define LOG_TO_STRING_FATAL(message) google::LogMessage( \
  370. __FILE__, __LINE__, google::FATAL, message)
  371. #else
  372. #define COMPACT_GOOGLE_LOG_FATAL google::NullStreamFatal()
  373. #define LOG_TO_STRING_FATAL(message) google::NullStreamFatal()
  374. #endif
  375. // For DFATAL, we want to use LogMessage (as opposed to
  376. // LogMessageFatal), to be consistent with the original behavior.
  377. #ifdef NDEBUG
  378. #define COMPACT_GOOGLE_LOG_DFATAL COMPACT_GOOGLE_LOG_ERROR
  379. #elif GOOGLE_STRIP_LOG <= 3
  380. #define COMPACT_GOOGLE_LOG_DFATAL google::LogMessage( \
  381. __FILE__, __LINE__, google::FATAL)
  382. #else
  383. #define COMPACT_GOOGLE_LOG_DFATAL google::NullStreamFatal()
  384. #endif
  385. #define GOOGLE_LOG_INFO(counter) google::LogMessage(__FILE__, __LINE__, google::INFO, counter, &google::LogMessage::SendToLog)
  386. #define SYSLOG_INFO(counter) \
  387. google::LogMessage(__FILE__, __LINE__, google::INFO, counter, \
  388. &google::LogMessage::SendToSyslogAndLog)
  389. #define GOOGLE_LOG_WARNING(counter) \
  390. google::LogMessage(__FILE__, __LINE__, google::WARNING, counter, \
  391. &google::LogMessage::SendToLog)
  392. #define SYSLOG_WARNING(counter) \
  393. google::LogMessage(__FILE__, __LINE__, google::WARNING, counter, \
  394. &google::LogMessage::SendToSyslogAndLog)
  395. #define GOOGLE_LOG_ERROR(counter) \
  396. google::LogMessage(__FILE__, __LINE__, google::ERROR, counter, \
  397. &google::LogMessage::SendToLog)
  398. #define SYSLOG_ERROR(counter) \
  399. google::LogMessage(__FILE__, __LINE__, google::ERROR, counter, \
  400. &google::LogMessage::SendToSyslogAndLog)
  401. #define GOOGLE_LOG_FATAL(counter) \
  402. google::LogMessage(__FILE__, __LINE__, google::FATAL, counter, \
  403. &google::LogMessage::SendToLog)
  404. #define SYSLOG_FATAL(counter) \
  405. google::LogMessage(__FILE__, __LINE__, google::FATAL, counter, \
  406. &google::LogMessage::SendToSyslogAndLog)
  407. #define GOOGLE_LOG_DFATAL(counter) \
  408. google::LogMessage(__FILE__, __LINE__, google::DFATAL_LEVEL, counter, \
  409. &google::LogMessage::SendToLog)
  410. #define SYSLOG_DFATAL(counter) \
  411. google::LogMessage(__FILE__, __LINE__, google::DFATAL_LEVEL, counter, \
  412. &google::LogMessage::SendToSyslogAndLog)
  413. #if defined(WIN32) || defined(_WIN32) || defined(__WIN32__) || defined(__CYGWIN__) || defined(__CYGWIN32__)
  414. // A very useful logging macro to log windows errors:
  415. #define LOG_SYSRESULT(result) \
  416. if (FAILED(result)) { \
  417. LPTSTR message = NULL; \
  418. LPTSTR msg = reinterpret_cast<LPTSTR>(&message); \
  419. DWORD message_length = FormatMessage(FORMAT_MESSAGE_ALLOCATE_BUFFER | \
  420. FORMAT_MESSAGE_FROM_SYSTEM, \
  421. 0, result, 0, msg, 100, NULL); \
  422. if (message_length > 0) { \
  423. google::LogMessage(__FILE__, __LINE__, ERROR, 0, \
  424. &google::LogMessage::SendToLog).stream() << message; \
  425. LocalFree(message); \
  426. } \
  427. }
  428. #endif
  429. // We use the preprocessor's merging operator, "##", so that, e.g.,
  430. // LOG(INFO) becomes the token GOOGLE_LOG_INFO. There's some funny
  431. // subtle difference between ostream member streaming functions (e.g.,
  432. // ostream::operator<<(int) and ostream non-member streaming functions
  433. // (e.g., ::operator<<(ostream&, string&): it turns out that it's
  434. // impossible to stream something like a string directly to an unnamed
  435. // ostream. We employ a neat hack by calling the stream() member
  436. // function of LogMessage which seems to avoid the problem.
  437. #define LOG(severity) COMPACT_GOOGLE_LOG_ ## severity.stream()
  438. #define SYSLOG(severity) SYSLOG_ ## severity(0).stream()
  439. namespace google {
  440. // They need the definitions of integer types.
  441. #include "glog/log_severity.h"
  442. #include "glog/vlog_is_on.h"
  443. // Initialize google's logging library. You will see the program name
  444. // specified by argv0 in log outputs.
  445. GOOGLE_GLOG_DLL_DECL void InitGoogleLogging(const char* argv0);
  446. // Shutdown google's logging library.
  447. GOOGLE_GLOG_DLL_DECL void ShutdownGoogleLogging();
  448. // Install a function which will be called after LOG(FATAL).
  449. GOOGLE_GLOG_DLL_DECL void InstallFailureFunction(void (*fail_func)());
  450. class LogSink; // defined below
  451. // If a non-NULL sink pointer is given, we push this message to that sink.
  452. // For LOG_TO_SINK we then do normal LOG(severity) logging as well.
  453. // This is useful for capturing messages and passing/storing them
  454. // somewhere more specific than the global log of the process.
  455. // Argument types:
  456. // LogSink* sink;
  457. // LogSeverity severity;
  458. // The cast is to disambiguate NULL arguments.
  459. #define LOG_TO_SINK(sink, severity) \
  460. google::LogMessage( \
  461. __FILE__, __LINE__, \
  462. google::severity, \
  463. static_cast<google::LogSink*>(sink), true).stream()
  464. #define LOG_TO_SINK_BUT_NOT_TO_LOGFILE(sink, severity) \
  465. google::LogMessage( \
  466. __FILE__, __LINE__, \
  467. google::severity, \
  468. static_cast<google::LogSink*>(sink), false).stream()
  469. // If a non-NULL string pointer is given, we write this message to that string.
  470. // We then do normal LOG(severity) logging as well.
  471. // This is useful for capturing messages and storing them somewhere more
  472. // specific than the global log of the process.
  473. // Argument types:
  474. // string* message;
  475. // LogSeverity severity;
  476. // The cast is to disambiguate NULL arguments.
  477. // NOTE: LOG(severity) expands to LogMessage().stream() for the specified
  478. // severity.
  479. #define LOG_TO_STRING(severity, message) \
  480. LOG_TO_STRING_##severity(static_cast<string*>(message)).stream()
  481. // If a non-NULL pointer is given, we push the message onto the end
  482. // of a vector of strings; otherwise, we report it with LOG(severity).
  483. // This is handy for capturing messages and perhaps passing them back
  484. // to the caller, rather than reporting them immediately.
  485. // Argument types:
  486. // LogSeverity severity;
  487. // vector<string> *outvec;
  488. // The cast is to disambiguate NULL arguments.
  489. #define LOG_STRING(severity, outvec) \
  490. LOG_TO_STRING_##severity(static_cast<vector<string>*>(outvec)).stream()
  491. #define LOG_IF(severity, condition) \
  492. !(condition) ? (void) 0 : google::LogMessageVoidify() & LOG(severity)
  493. #define SYSLOG_IF(severity, condition) \
  494. !(condition) ? (void) 0 : google::LogMessageVoidify() & SYSLOG(severity)
  495. #define LOG_ASSERT(condition) \
  496. LOG_IF(FATAL, !(condition)) << "Assert failed: " #condition
  497. #define SYSLOG_ASSERT(condition) \
  498. SYSLOG_IF(FATAL, !(condition)) << "Assert failed: " #condition
  499. // CHECK dies with a fatal error if condition is not true. It is *not*
  500. // controlled by NDEBUG, so the check will be executed regardless of
  501. // compilation mode. Therefore, it is safe to do things like:
  502. // CHECK(fp->Write(x) == 4)
  503. #define CHECK(condition) \
  504. LOG_IF(FATAL, GOOGLE_PREDICT_BRANCH_NOT_TAKEN(!(condition))) \
  505. << "Check failed: " #condition " "
  506. // A container for a string pointer which can be evaluated to a bool -
  507. // true iff the pointer is NULL.
  508. struct CheckOpString {
  509. CheckOpString(std::string* str) : str_(str) { }
  510. // No destructor: if str_ is non-NULL, we're about to LOG(FATAL),
  511. // so there's no point in cleaning up str_.
  512. operator bool() const {
  513. return GOOGLE_PREDICT_BRANCH_NOT_TAKEN(str_ != NULL);
  514. }
  515. std::string* str_;
  516. };
  517. // Function is overloaded for integral types to allow static const
  518. // integrals declared in classes and not defined to be used as arguments to
  519. // CHECK* macros. It's not encouraged though.
  520. template <class T>
  521. inline const T& GetReferenceableValue(const T& t) { return t; }
  522. inline char GetReferenceableValue(char t) { return t; }
  523. inline unsigned char GetReferenceableValue(unsigned char t) { return t; }
  524. inline signed char GetReferenceableValue(signed char t) { return t; }
  525. inline short GetReferenceableValue(short t) { return t; }
  526. inline unsigned short GetReferenceableValue(unsigned short t) { return t; }
  527. inline int GetReferenceableValue(int t) { return t; }
  528. inline unsigned int GetReferenceableValue(unsigned int t) { return t; }
  529. inline long GetReferenceableValue(long t) { return t; }
  530. inline unsigned long GetReferenceableValue(unsigned long t) { return t; }
  531. inline long long GetReferenceableValue(long long t) { return t; }
  532. inline unsigned long long GetReferenceableValue(unsigned long long t) {
  533. return t;
  534. }
  535. // This is a dummy class to define the following operator.
  536. struct DummyClassToDefineOperator {};
  537. }
  538. // Define global operator<< to declare using ::operator<<.
  539. // This declaration will allow use to use CHECK macros for user
  540. // defined classes which have operator<< (e.g., stl_logging.h).
  541. inline std::ostream& operator<<(
  542. std::ostream& out, const google::DummyClassToDefineOperator&) {
  543. return out;
  544. }
  545. namespace google {
  546. // Build the error message string.
  547. template<class t1, class t2>
  548. std::string* MakeCheckOpString(const t1& v1, const t2& v2, const char* names) {
  549. // It means that we cannot use stl_logging if compiler doesn't
  550. // support using expression for operator.
  551. // TODO(hamaji): Figure out a way to fix.
  552. #if 1
  553. using ::operator<<;
  554. #endif
  555. std::strstream ss;
  556. ss << names << " (" << v1 << " vs. " << v2 << ")";
  557. return new std::string(ss.str(), ss.pcount());
  558. }
  559. // Helper functions for CHECK_OP macro.
  560. // The (int, int) specialization works around the issue that the compiler
  561. // will not instantiate the template version of the function on values of
  562. // unnamed enum type - see comment below.
  563. #define DEFINE_CHECK_OP_IMPL(name, op) \
  564. template <class t1, class t2> \
  565. inline std::string* Check##name##Impl(const t1& v1, const t2& v2, \
  566. const char* names) { \
  567. if (v1 op v2) return NULL; \
  568. else return MakeCheckOpString(v1, v2, names); \
  569. } \
  570. inline std::string* Check##name##Impl(int v1, int v2, const char* names) { \
  571. return Check##name##Impl<int, int>(v1, v2, names); \
  572. }
  573. // Use _EQ, _NE, _LE, etc. in case the file including base/logging.h
  574. // provides its own #defines for the simpler names EQ, NE, LE, etc.
  575. // This happens if, for example, those are used as token names in a
  576. // yacc grammar.
  577. DEFINE_CHECK_OP_IMPL(_EQ, ==)
  578. DEFINE_CHECK_OP_IMPL(_NE, !=)
  579. DEFINE_CHECK_OP_IMPL(_LE, <=)
  580. DEFINE_CHECK_OP_IMPL(_LT, < )
  581. DEFINE_CHECK_OP_IMPL(_GE, >=)
  582. DEFINE_CHECK_OP_IMPL(_GT, > )
  583. #undef DEFINE_CHECK_OP_IMPL
  584. // Helper macro for binary operators.
  585. // Don't use this macro directly in your code, use CHECK_EQ et al below.
  586. #if defined(STATIC_ANALYSIS)
  587. // Only for static analysis tool to know that it is equivalent to assert
  588. #define CHECK_OP_LOG(name, op, val1, val2, log) CHECK((val1) op (val2))
  589. #elif !defined(NDEBUG)
  590. // In debug mode, avoid constructing CheckOpStrings if possible,
  591. // to reduce the overhead of CHECK statments by 2x.
  592. // Real DCHECK-heavy tests have seen 1.5x speedups.
  593. // The meaning of "string" might be different between now and
  594. // when this macro gets invoked (e.g., if someone is experimenting
  595. // with other string implementations that get defined after this
  596. // file is included). Save the current meaning now and use it
  597. // in the macro.
  598. typedef std::string _Check_string;
  599. #define CHECK_OP_LOG(name, op, val1, val2, log) \
  600. while (google::_Check_string* _result = \
  601. google::Check##name##Impl( \
  602. google::GetReferenceableValue(val1), \
  603. google::GetReferenceableValue(val2), \
  604. #val1 " " #op " " #val2)) \
  605. log(__FILE__, __LINE__, \
  606. google::CheckOpString(_result)).stream()
  607. #else
  608. // In optimized mode, use CheckOpString to hint to compiler that
  609. // the while condition is unlikely.
  610. #define CHECK_OP_LOG(name, op, val1, val2, log) \
  611. while (google::CheckOpString _result = \
  612. google::Check##name##Impl( \
  613. google::GetReferenceableValue(val1), \
  614. google::GetReferenceableValue(val2), \
  615. #val1 " " #op " " #val2)) \
  616. log(__FILE__, __LINE__, _result).stream()
  617. #endif // STATIC_ANALYSIS, !NDEBUG
  618. #if GOOGLE_STRIP_LOG <= 3
  619. #define CHECK_OP(name, op, val1, val2) \
  620. CHECK_OP_LOG(name, op, val1, val2, google::LogMessageFatal)
  621. #else
  622. #define CHECK_OP(name, op, val1, val2) \
  623. CHECK_OP_LOG(name, op, val1, val2, google::NullStreamFatal)
  624. #endif // STRIP_LOG <= 3
  625. // Equality/Inequality checks - compare two values, and log a FATAL message
  626. // including the two values when the result is not as expected. The values
  627. // must have operator<<(ostream, ...) defined.
  628. //
  629. // You may append to the error message like so:
  630. // CHECK_NE(1, 2) << ": The world must be ending!";
  631. //
  632. // We are very careful to ensure that each argument is evaluated exactly
  633. // once, and that anything which is legal to pass as a function argument is
  634. // legal here. In particular, the arguments may be temporary expressions
  635. // which will end up being destroyed at the end of the apparent statement,
  636. // for example:
  637. // CHECK_EQ(string("abc")[1], 'b');
  638. //
  639. // WARNING: These don't compile correctly if one of the arguments is a pointer
  640. // and the other is NULL. To work around this, simply static_cast NULL to the
  641. // type of the desired pointer.
  642. #define CHECK_EQ(val1, val2) CHECK_OP(_EQ, ==, val1, val2)
  643. #define CHECK_NE(val1, val2) CHECK_OP(_NE, !=, val1, val2)
  644. #define CHECK_LE(val1, val2) CHECK_OP(_LE, <=, val1, val2)
  645. #define CHECK_LT(val1, val2) CHECK_OP(_LT, < , val1, val2)
  646. #define CHECK_GE(val1, val2) CHECK_OP(_GE, >=, val1, val2)
  647. #define CHECK_GT(val1, val2) CHECK_OP(_GT, > , val1, val2)
  648. // Check that the input is non NULL. This very useful in constructor
  649. // initializer lists.
  650. #define CHECK_NOTNULL(val) \
  651. google::CheckNotNull(__FILE__, __LINE__, "'" #val "' Must be non NULL", (val))
  652. // Helper functions for string comparisons.
  653. // To avoid bloat, the definitions are in logging.cc.
  654. #define DECLARE_CHECK_STROP_IMPL(func, expected) \
  655. GOOGLE_GLOG_DLL_DECL std::string* Check##func##expected##Impl( \
  656. const char* s1, const char* s2, const char* names);
  657. DECLARE_CHECK_STROP_IMPL(strcmp, true)
  658. DECLARE_CHECK_STROP_IMPL(strcmp, false)
  659. DECLARE_CHECK_STROP_IMPL(strcasecmp, true)
  660. DECLARE_CHECK_STROP_IMPL(strcasecmp, false)
  661. #undef DECLARE_CHECK_STROP_IMPL
  662. // Helper macro for string comparisons.
  663. // Don't use this macro directly in your code, use CHECK_STREQ et al below.
  664. #define CHECK_STROP(func, op, expected, s1, s2) \
  665. while (google::CheckOpString _result = \
  666. google::Check##func##expected##Impl((s1), (s2), \
  667. #s1 " " #op " " #s2)) \
  668. LOG(FATAL) << *_result.str_
  669. // String (char*) equality/inequality checks.
  670. // CASE versions are case-insensitive.
  671. //
  672. // Note that "s1" and "s2" may be temporary strings which are destroyed
  673. // by the compiler at the end of the current "full expression"
  674. // (e.g. CHECK_STREQ(Foo().c_str(), Bar().c_str())).
  675. #define CHECK_STREQ(s1, s2) CHECK_STROP(strcmp, ==, true, s1, s2)
  676. #define CHECK_STRNE(s1, s2) CHECK_STROP(strcmp, !=, false, s1, s2)
  677. #define CHECK_STRCASEEQ(s1, s2) CHECK_STROP(strcasecmp, ==, true, s1, s2)
  678. #define CHECK_STRCASENE(s1, s2) CHECK_STROP(strcasecmp, !=, false, s1, s2)
  679. #define CHECK_INDEX(I,A) CHECK(I < (sizeof(A)/sizeof(A[0])))
  680. #define CHECK_BOUND(B,A) CHECK(B <= (sizeof(A)/sizeof(A[0])))
  681. #define CHECK_DOUBLE_EQ(val1, val2) \
  682. do { \
  683. CHECK_LE((val1), (val2)+0.000000000000001L); \
  684. CHECK_GE((val1), (val2)-0.000000000000001L); \
  685. } while (0)
  686. #define CHECK_NEAR(val1, val2, margin) \
  687. do { \
  688. CHECK_LE((val1), (val2)+(margin)); \
  689. CHECK_GE((val1), (val2)-(margin)); \
  690. } while (0)
  691. // perror()..googly style!
  692. //
  693. // PLOG() and PLOG_IF() and PCHECK() behave exactly like their LOG* and
  694. // CHECK equivalents with the addition that they postpend a description
  695. // of the current state of errno to their output lines.
  696. #define PLOG(severity) GOOGLE_PLOG(severity, 0).stream()
  697. #define GOOGLE_PLOG(severity, counter) \
  698. google::ErrnoLogMessage( \
  699. __FILE__, __LINE__, google::severity, counter, \
  700. &google::LogMessage::SendToLog)
  701. #define PLOG_IF(severity, condition) \
  702. !(condition) ? (void) 0 : google::LogMessageVoidify() & PLOG(severity)
  703. // A CHECK() macro that postpends errno if the condition is false. E.g.
  704. //
  705. // if (poll(fds, nfds, timeout) == -1) { PCHECK(errno == EINTR); ... }
  706. #define PCHECK(condition) \
  707. PLOG_IF(FATAL, GOOGLE_PREDICT_BRANCH_NOT_TAKEN(!(condition))) \
  708. << "Check failed: " #condition " "
  709. // A CHECK() macro that lets you assert the success of a function that
  710. // returns -1 and sets errno in case of an error. E.g.
  711. //
  712. // CHECK_ERR(mkdir(path, 0700));
  713. //
  714. // or
  715. //
  716. // int fd = open(filename, flags); CHECK_ERR(fd) << ": open " << filename;
  717. #define CHECK_ERR(invocation) \
  718. PLOG_IF(FATAL, GOOGLE_PREDICT_BRANCH_NOT_TAKEN((invocation) == -1)) \
  719. << #invocation
  720. // Use macro expansion to create, for each use of LOG_EVERY_N(), static
  721. // variables with the __LINE__ expansion as part of the variable name.
  722. #define LOG_EVERY_N_VARNAME(base, line) LOG_EVERY_N_VARNAME_CONCAT(base, line)
  723. #define LOG_EVERY_N_VARNAME_CONCAT(base, line) base ## line
  724. #define LOG_OCCURRENCES LOG_EVERY_N_VARNAME(occurrences_, __LINE__)
  725. #define LOG_OCCURRENCES_MOD_N LOG_EVERY_N_VARNAME(occurrences_mod_n_, __LINE__)
  726. #define SOME_KIND_OF_LOG_EVERY_N(severity, n, what_to_do) \
  727. static int LOG_OCCURRENCES = 0, LOG_OCCURRENCES_MOD_N = 0; \
  728. ++LOG_OCCURRENCES; \
  729. if (++LOG_OCCURRENCES_MOD_N > n) LOG_OCCURRENCES_MOD_N -= n; \
  730. if (LOG_OCCURRENCES_MOD_N == 1) \
  731. google::LogMessage( \
  732. __FILE__, __LINE__, google::severity, LOG_OCCURRENCES, \
  733. &what_to_do).stream()
  734. #define SOME_KIND_OF_LOG_IF_EVERY_N(severity, condition, n, what_to_do) \
  735. static int LOG_OCCURRENCES = 0, LOG_OCCURRENCES_MOD_N = 0; \
  736. ++LOG_OCCURRENCES; \
  737. if (condition && \
  738. ((LOG_OCCURRENCES_MOD_N=(LOG_OCCURRENCES_MOD_N + 1) % n) == (1 % n))) \
  739. google::LogMessage( \
  740. __FILE__, __LINE__, google::severity, LOG_OCCURRENCES, \
  741. &what_to_do).stream()
  742. #define SOME_KIND_OF_PLOG_EVERY_N(severity, n, what_to_do) \
  743. static int LOG_OCCURRENCES = 0, LOG_OCCURRENCES_MOD_N = 0; \
  744. ++LOG_OCCURRENCES; \
  745. if (++LOG_OCCURRENCES_MOD_N > n) LOG_OCCURRENCES_MOD_N -= n; \
  746. if (LOG_OCCURRENCES_MOD_N == 1) \
  747. google::ErrnoLogMessage( \
  748. __FILE__, __LINE__, google::severity, LOG_OCCURRENCES, \
  749. &what_to_do).stream()
  750. #define SOME_KIND_OF_LOG_FIRST_N(severity, n, what_to_do) \
  751. static int LOG_OCCURRENCES = 0; \
  752. if (LOG_OCCURRENCES <= n) \
  753. ++LOG_OCCURRENCES; \
  754. if (LOG_OCCURRENCES <= n) \
  755. google::LogMessage( \
  756. __FILE__, __LINE__, google::severity, LOG_OCCURRENCES, \
  757. &what_to_do).stream()
  758. namespace glog_internal_namespace_ {
  759. template <bool>
  760. struct CompileAssert {
  761. };
  762. struct CrashReason;
  763. } // namespace glog_internal_namespace_
  764. #define GOOGLE_GLOG_COMPILE_ASSERT(expr, msg) \
  765. typedef google::glog_internal_namespace_::CompileAssert<(bool(expr))> msg[bool(expr) ? 1 : -1]
  766. #define LOG_EVERY_N(severity, n) \
  767. GOOGLE_GLOG_COMPILE_ASSERT(google::severity < \
  768. google::NUM_SEVERITIES, \
  769. INVALID_REQUESTED_LOG_SEVERITY); \
  770. SOME_KIND_OF_LOG_EVERY_N(severity, (n), google::LogMessage::SendToLog)
  771. #define SYSLOG_EVERY_N(severity, n) \
  772. SOME_KIND_OF_LOG_EVERY_N(severity, (n), google::LogMessage::SendToSyslogAndLog)
  773. #define PLOG_EVERY_N(severity, n) \
  774. SOME_KIND_OF_PLOG_EVERY_N(severity, (n), google::LogMessage::SendToLog)
  775. #define LOG_FIRST_N(severity, n) \
  776. SOME_KIND_OF_LOG_FIRST_N(severity, (n), google::LogMessage::SendToLog)
  777. #define LOG_IF_EVERY_N(severity, condition, n) \
  778. SOME_KIND_OF_LOG_IF_EVERY_N(severity, (condition), (n), google::LogMessage::SendToLog)
  779. // We want the special COUNTER value available for LOG_EVERY_X()'ed messages
  780. enum PRIVATE_Counter {COUNTER};
  781. // Plus some debug-logging macros that get compiled to nothing for production
  782. #ifndef NDEBUG
  783. #define DLOG(severity) LOG(severity)
  784. #define DVLOG(verboselevel) VLOG(verboselevel)
  785. #define DLOG_IF(severity, condition) LOG_IF(severity, condition)
  786. #define DLOG_EVERY_N(severity, n) LOG_EVERY_N(severity, n)
  787. #define DLOG_IF_EVERY_N(severity, condition, n) \
  788. LOG_IF_EVERY_N(severity, condition, n)
  789. #define DLOG_ASSERT(condition) LOG_ASSERT(condition)
  790. // debug-only checking. not executed in NDEBUG mode.
  791. #define DCHECK(condition) CHECK(condition)
  792. #define DCHECK_EQ(val1, val2) CHECK_EQ(val1, val2)
  793. #define DCHECK_NE(val1, val2) CHECK_NE(val1, val2)
  794. #define DCHECK_LE(val1, val2) CHECK_LE(val1, val2)
  795. #define DCHECK_LT(val1, val2) CHECK_LT(val1, val2)
  796. #define DCHECK_GE(val1, val2) CHECK_GE(val1, val2)
  797. #define DCHECK_GT(val1, val2) CHECK_GT(val1, val2)
  798. #define DCHECK_NOTNULL(val) CHECK_NOTNULL(val)
  799. #define DCHECK_STREQ(str1, str2) CHECK_STREQ(str1, str2)
  800. #define DCHECK_STRCASEEQ(str1, str2) CHECK_STRCASEEQ(str1, str2)
  801. #define DCHECK_STRNE(str1, str2) CHECK_STRNE(str1, str2)
  802. #define DCHECK_STRCASENE(str1, str2) CHECK_STRCASENE(str1, str2)
  803. #else // NDEBUG
  804. #define DLOG(severity) \
  805. true ? (void) 0 : google::LogMessageVoidify() & LOG(severity)
  806. #define DVLOG(verboselevel) \
  807. (true || !VLOG_IS_ON(verboselevel)) ?\
  808. (void) 0 : google::LogMessageVoidify() & LOG(INFO)
  809. #define DLOG_IF(severity, condition) \
  810. (true || !(condition)) ? (void) 0 : google::LogMessageVoidify() & LOG(severity)
  811. #define DLOG_EVERY_N(severity, n) \
  812. true ? (void) 0 : google::LogMessageVoidify() & LOG(severity)
  813. #define DLOG_IF_EVERY_N(severity, condition, n) \
  814. (true || !(condition))? (void) 0 : google::LogMessageVoidify() & LOG(severity)
  815. #define DLOG_ASSERT(condition) \
  816. true ? (void) 0 : LOG_ASSERT(condition)
  817. #define DCHECK(condition) \
  818. while (false) \
  819. CHECK(condition)
  820. #define DCHECK_EQ(val1, val2) \
  821. while (false) \
  822. CHECK_EQ(val1, val2)
  823. #define DCHECK_NE(val1, val2) \
  824. while (false) \
  825. CHECK_NE(val1, val2)
  826. #define DCHECK_LE(val1, val2) \
  827. while (false) \
  828. CHECK_LE(val1, val2)
  829. #define DCHECK_LT(val1, val2) \
  830. while (false) \
  831. CHECK_LT(val1, val2)
  832. #define DCHECK_GE(val1, val2) \
  833. while (false) \
  834. CHECK_GE(val1, val2)
  835. #define DCHECK_GT(val1, val2) \
  836. while (false) \
  837. CHECK_GT(val1, val2)
  838. #define DCHECK_NOTNULL(val) (val)
  839. #define DCHECK_STREQ(str1, str2) \
  840. while (false) \
  841. CHECK_STREQ(str1, str2)
  842. #define DCHECK_STRCASEEQ(str1, str2) \
  843. while (false) \
  844. CHECK_STRCASEEQ(str1, str2)
  845. #define DCHECK_STRNE(str1, str2) \
  846. while (false) \
  847. CHECK_STRNE(str1, str2)
  848. #define DCHECK_STRCASENE(str1, str2) \
  849. while (false) \
  850. CHECK_STRCASENE(str1, str2)
  851. #endif // NDEBUG
  852. // Log only in verbose mode.
  853. #define VLOG(verboselevel) LOG_IF(INFO, VLOG_IS_ON(verboselevel))
  854. #define VLOG_IF(verboselevel, condition) \
  855. LOG_IF(INFO, (condition) && VLOG_IS_ON(verboselevel))
  856. #define VLOG_EVERY_N(verboselevel, n) \
  857. LOG_IF_EVERY_N(INFO, VLOG_IS_ON(verboselevel), n)
  858. #define VLOG_IF_EVERY_N(verboselevel, condition, n) \
  859. LOG_IF_EVERY_N(INFO, (condition) && VLOG_IS_ON(verboselevel), n)
  860. //
  861. // This class more or less represents a particular log message. You
  862. // create an instance of LogMessage and then stream stuff to it.
  863. // When you finish streaming to it, ~LogMessage is called and the
  864. // full message gets streamed to the appropriate destination.
  865. //
  866. // You shouldn't actually use LogMessage's constructor to log things,
  867. // though. You should use the LOG() macro (and variants thereof)
  868. // above.
  869. class GOOGLE_GLOG_DLL_DECL LogMessage {
  870. public:
  871. enum {
  872. // Passing kNoLogPrefix for the line number disables the
  873. // log-message prefix. Useful for using the LogMessage
  874. // infrastructure as a printing utility. See also the --log_prefix
  875. // flag for controlling the log-message prefix on an
  876. // application-wide basis.
  877. kNoLogPrefix = -1
  878. };
  879. // LogStream inherit from non-DLL-exported class (std::ostrstream)
  880. // and VC++ produces a warning for this situation.
  881. // However, MSDN says "C4275 can be ignored in Microsoft Visual C++
  882. // 2005 if you are deriving from a type in the Standard C++ Library"
  883. // http://msdn.microsoft.com/en-us/library/3tdb471s(VS.80).aspx
  884. // Let's just ignore the warning.
  885. #ifdef _MSC_VER
  886. # pragma warning(disable: 4275)
  887. #endif
  888. class GOOGLE_GLOG_DLL_DECL LogStream : public std::ostrstream {
  889. #ifdef _MSC_VER
  890. # pragma warning(default: 4275)
  891. #endif
  892. public:
  893. LogStream(char *buf, int len, int ctr)
  894. : ostrstream(buf, len),
  895. ctr_(ctr) {
  896. self_ = this;
  897. }
  898. int ctr() const { return ctr_; }
  899. void set_ctr(int ctr) { ctr_ = ctr; }
  900. LogStream* self() const { return self_; }
  901. private:
  902. int ctr_; // Counter hack (for the LOG_EVERY_X() macro)
  903. LogStream *self_; // Consistency check hack
  904. };
  905. public:
  906. // icc 8 requires this typedef to avoid an internal compiler error.
  907. typedef void (LogMessage::*SendMethod)();
  908. LogMessage(const char* file, int line, LogSeverity severity, int ctr,
  909. SendMethod send_method);
  910. // Two special constructors that generate reduced amounts of code at
  911. // LOG call sites for common cases.
  912. // Used for LOG(INFO): Implied are:
  913. // severity = INFO, ctr = 0, send_method = &LogMessage::SendToLog.
  914. //
  915. // Using this constructor instead of the more complex constructor above
  916. // saves 19 bytes per call site.
  917. LogMessage(const char* file, int line);
  918. // Used for LOG(severity) where severity != INFO. Implied
  919. // are: ctr = 0, send_method = &LogMessage::SendToLog
  920. //
  921. // Using this constructor instead of the more complex constructor above
  922. // saves 17 bytes per call site.
  923. LogMessage(const char* file, int line, LogSeverity severity);
  924. // Constructor to log this message to a specified sink (if not NULL).
  925. // Implied are: ctr = 0, send_method = &LogMessage::SendToSinkAndLog if
  926. // also_send_to_log is true, send_method = &LogMessage::SendToSink otherwise.
  927. LogMessage(const char* file, int line, LogSeverity severity, LogSink* sink,
  928. bool also_send_to_log);
  929. // Constructor where we also give a vector<string> pointer
  930. // for storing the messages (if the pointer is not NULL).
  931. // Implied are: ctr = 0, send_method = &LogMessage::SaveOrSendToLog.
  932. LogMessage(const char* file, int line, LogSeverity severity,
  933. std::vector<std::string>* outvec);
  934. // Constructor where we also give a string pointer for storing the
  935. // message (if the pointer is not NULL). Implied are: ctr = 0,
  936. // send_method = &LogMessage::WriteToStringAndLog.
  937. LogMessage(const char* file, int line, LogSeverity severity,
  938. std::string* message);
  939. // A special constructor used for check failures
  940. LogMessage(const char* file, int line, const CheckOpString& result);
  941. ~LogMessage();
  942. // Flush a buffered message to the sink set in the constructor. Always
  943. // called by the destructor, it may also be called from elsewhere if
  944. // needed. Only the first call is actioned; any later ones are ignored.
  945. void Flush();
  946. // An arbitrary limit on the length of a single log message. This
  947. // is so that streaming can be done more efficiently.
  948. static const size_t kMaxLogMessageLen;
  949. // Theses should not be called directly outside of logging.*,
  950. // only passed as SendMethod arguments to other LogMessage methods:
  951. void SendToLog(); // Actually dispatch to the logs
  952. void SendToSyslogAndLog(); // Actually dispatch to syslog and the logs
  953. // Call abort() or similar to perform LOG(FATAL) crash.
  954. static void Fail() ;
  955. std::ostream& stream() { return *(data_->stream_); }
  956. int preserved_errno() const { return data_->preserved_errno_; }
  957. // Must be called without the log_mutex held. (L < log_mutex)
  958. static int64 num_messages(int severity);
  959. private:
  960. // Fully internal SendMethod cases:
  961. void SendToSinkAndLog(); // Send to sink if provided and dispatch to the logs
  962. void SendToSink(); // Send to sink if provided, do nothing otherwise.
  963. // Write to string if provided and dispatch to the logs.
  964. void WriteToStringAndLog();
  965. void SaveOrSendToLog(); // Save to stringvec if provided, else to logs
  966. void Init(const char* file, int line, LogSeverity severity,
  967. void (LogMessage::*send_method)());
  968. // Used to fill in crash information during LOG(FATAL) failures.
  969. void RecordCrashReason(glog_internal_namespace_::CrashReason* reason);
  970. // Counts of messages sent at each priority:
  971. static int64 num_messages_[NUM_SEVERITIES]; // under log_mutex
  972. // We keep the data in a separate struct so that each instance of
  973. // LogMessage uses less stack space.
  974. struct GOOGLE_GLOG_DLL_DECL LogMessageData {
  975. LogMessageData() {};
  976. int preserved_errno_; // preserved errno
  977. char* buf_;
  978. char* message_text_; // Complete message text (points to selected buffer)
  979. LogStream* stream_alloc_;
  980. LogStream* stream_;
  981. char severity_; // What level is this LogMessage logged at?
  982. int line_; // line number where logging call is.
  983. void (LogMessage::*send_method_)(); // Call this in destructor to send
  984. union { // At most one of these is used: union to keep the size low.
  985. LogSink* sink_; // NULL or sink to send message to
  986. std::vector<std::string>* outvec_; // NULL or vector to push message onto
  987. std::string* message_; // NULL or string to write message into
  988. };
  989. time_t timestamp_; // Time of creation of LogMessage
  990. struct ::tm tm_time_; // Time of creation of LogMessage
  991. size_t num_prefix_chars_; // # of chars of prefix in this message
  992. size_t num_chars_to_log_; // # of chars of msg to send to log
  993. size_t num_chars_to_syslog_; // # of chars of msg to send to syslog
  994. const char* basename_; // basename of file that called LOG
  995. const char* fullname_; // fullname of file that called LOG
  996. bool has_been_flushed_; // false => data has not been flushed
  997. bool first_fatal_; // true => this was first fatal msg
  998. ~LogMessageData();
  999. private:
  1000. LogMessageData(const LogMessageData&);
  1001. void operator=(const LogMessageData&);
  1002. };
  1003. static LogMessageData fatal_msg_data_exclusive_;
  1004. static LogMessageData fatal_msg_data_shared_;
  1005. LogMessageData* allocated_;
  1006. LogMessageData* data_;
  1007. friend class LogDestination;
  1008. LogMessage(const LogMessage&);
  1009. void operator=(const LogMessage&);
  1010. };
  1011. // This class happens to be thread-hostile because all instances share
  1012. // a single data buffer, but since it can only be created just before
  1013. // the process dies, we don't worry so much.
  1014. class GOOGLE_GLOG_DLL_DECL LogMessageFatal : public LogMessage {
  1015. public:
  1016. LogMessageFatal(const char* file, int line);
  1017. LogMessageFatal(const char* file, int line, const CheckOpString& result);
  1018. ~LogMessageFatal() ;
  1019. };
  1020. // A non-macro interface to the log facility; (useful
  1021. // when the logging level is not a compile-time constant).
  1022. inline void LogAtLevel(int const severity, std::string const &msg) {
  1023. LogMessage(__FILE__, __LINE__, severity).stream() << msg;
  1024. }
  1025. // A macro alternative of LogAtLevel. New code may want to use this
  1026. // version since there are two advantages: 1. this version outputs the
  1027. // file name and the line number where this macro is put like other
  1028. // LOG macros, 2. this macro can be used as C++ stream.
  1029. #define LOG_AT_LEVEL(severity) google::LogMessage(__FILE__, __LINE__, severity).stream()
  1030. // A small helper for CHECK_NOTNULL().
  1031. template <typename T>
  1032. T* CheckNotNull(const char *file, int line, const char *names, T* t) {
  1033. if (t == NULL) {
  1034. LogMessageFatal(file, line, new std::string(names));
  1035. }
  1036. return t;
  1037. }
  1038. // Allow folks to put a counter in the LOG_EVERY_X()'ed messages. This
  1039. // only works if ostream is a LogStream. If the ostream is not a
  1040. // LogStream you'll get an assert saying as much at runtime.
  1041. GOOGLE_GLOG_DLL_DECL std::ostream& operator<<(std::ostream &os,
  1042. const PRIVATE_Counter&);
  1043. // Derived class for PLOG*() above.
  1044. class GOOGLE_GLOG_DLL_DECL ErrnoLogMessage : public LogMessage {
  1045. public:
  1046. ErrnoLogMessage(const char* file, int line, LogSeverity severity, int ctr,
  1047. void (LogMessage::*send_method)());
  1048. // Postpends ": strerror(errno) [errno]".
  1049. ~ErrnoLogMessage();
  1050. private:
  1051. ErrnoLogMessage(const ErrnoLogMessage&);
  1052. void operator=(const ErrnoLogMessage&);
  1053. };
  1054. // This class is used to explicitly ignore values in the conditional
  1055. // logging macros. This avoids compiler warnings like "value computed
  1056. // is not used" and "statement has no effect".
  1057. class GOOGLE_GLOG_DLL_DECL LogMessageVoidify {
  1058. public:
  1059. LogMessageVoidify() { }
  1060. // This has to be an operator with a precedence lower than << but
  1061. // higher than ?:
  1062. void operator&(std::ostream&) { }
  1063. };
  1064. // Flushes all log files that contains messages that are at least of
  1065. // the specified severity level. Thread-safe.
  1066. GOOGLE_GLOG_DLL_DECL void FlushLogFiles(LogSeverity min_severity);
  1067. // Flushes all log files that contains messages that are at least of
  1068. // the specified severity level. Thread-hostile because it ignores
  1069. // locking -- used for catastrophic failures.
  1070. GOOGLE_GLOG_DLL_DECL void FlushLogFilesUnsafe(LogSeverity min_severity);
  1071. //
  1072. // Set the destination to which a particular severity level of log
  1073. // messages is sent. If base_filename is "", it means "don't log this
  1074. // severity". Thread-safe.
  1075. //
  1076. GOOGLE_GLOG_DLL_DECL void SetLogDestination(LogSeverity severity,
  1077. const char* base_filename);
  1078. //
  1079. // Set the basename of the symlink to the latest log file at a given
  1080. // severity. If symlink_basename is empty, do not make a symlink. If
  1081. // you don't call this function, the symlink basename is the
  1082. // invocation name of the program. Thread-safe.
  1083. //
  1084. GOOGLE_GLOG_DLL_DECL void SetLogSymlink(LogSeverity severity,
  1085. const char* symlink_basename);
  1086. //
  1087. // Used to send logs to some other kind of destination
  1088. // Users should subclass LogSink and override send to do whatever they want.
  1089. // Implementations must be thread-safe because a shared instance will
  1090. // be called from whichever thread ran the LOG(XXX) line.
  1091. class GOOGLE_GLOG_DLL_DECL LogSink {
  1092. public:
  1093. virtual ~LogSink();
  1094. // Sink's logging logic (message_len is such as to exclude '\n' at the end).
  1095. // This method can't use LOG() or CHECK() as logging system mutex(s) are held
  1096. // during this call.
  1097. virtual void send(LogSeverity severity, const char* full_filename,
  1098. const char* base_filename, int line,
  1099. const struct ::tm* tm_time,
  1100. const char* message, size_t message_len) = 0;
  1101. // Redefine this to implement waiting for
  1102. // the sink's logging logic to complete.
  1103. // It will be called after each send() returns,
  1104. // but before that LogMessage exits or crashes.
  1105. // By default this function does nothing.
  1106. // Using this function one can implement complex logic for send()
  1107. // that itself involves logging; and do all this w/o causing deadlocks and
  1108. // inconsistent rearrangement of log messages.
  1109. // E.g. if a LogSink has thread-specific actions, the send() method
  1110. // can simply add the message to a queue and wake up another thread that
  1111. // handles real logging while itself making some LOG() calls;
  1112. // WaitTillSent() can be implemented to wait for that logic to complete.
  1113. // See our unittest for an example.
  1114. virtual void WaitTillSent();
  1115. // Returns the normal text output of the log message.
  1116. // Can be useful to implement send().
  1117. static std::string ToString(LogSeverity severity, const char* file, int line,
  1118. const struct ::tm* tm_time,
  1119. const char* message, size_t message_len);
  1120. };
  1121. // Add or remove a LogSink as a consumer of logging data. Thread-safe.
  1122. GOOGLE_GLOG_DLL_DECL void AddLogSink(LogSink *destination);
  1123. GOOGLE_GLOG_DLL_DECL void RemoveLogSink(LogSink *destination);
  1124. //
  1125. // Specify an "extension" added to the filename specified via
  1126. // SetLogDestination. This applies to all severity levels. It's
  1127. // often used to append the port we're listening on to the logfile
  1128. // name. Thread-safe.
  1129. //
  1130. GOOGLE_GLOG_DLL_DECL void SetLogFilenameExtension(
  1131. const char* filename_extension);
  1132. //
  1133. // Make it so that all log messages of at least a particular severity
  1134. // are logged to stderr (in addition to logging to the usual log
  1135. // file(s)). Thread-safe.
  1136. //
  1137. GOOGLE_GLOG_DLL_DECL void SetStderrLogging(LogSeverity min_severity);
  1138. //
  1139. // Make it so that all log messages go only to stderr. Thread-safe.
  1140. //
  1141. GOOGLE_GLOG_DLL_DECL void LogToStderr();
  1142. //
  1143. // Make it so that all log messages of at least a particular severity are
  1144. // logged via email to a list of addresses (in addition to logging to the
  1145. // usual log file(s)). The list of addresses is just a string containing
  1146. // the email addresses to send to (separated by spaces, say). Thread-safe.
  1147. //
  1148. GOOGLE_GLOG_DLL_DECL void SetEmailLogging(LogSeverity min_severity,
  1149. const char* addresses);
  1150. // A simple function that sends email. dest is a commma-separated
  1151. // list of addressess. Thread-safe.
  1152. GOOGLE_GLOG_DLL_DECL bool SendEmail(const char *dest,
  1153. const char *subject, const char *body);
  1154. GOOGLE_GLOG_DLL_DECL const std::vector<std::string>& GetLoggingDirectories();
  1155. // For tests only: Clear the internal [cached] list of logging directories to
  1156. // force a refresh the next time GetLoggingDirectories is called.
  1157. // Thread-hostile.
  1158. void TestOnly_ClearLoggingDirectoriesList();
  1159. // Returns a set of existing temporary directories, which will be a
  1160. // subset of the directories returned by GetLogginDirectories().
  1161. // Thread-safe.
  1162. GOOGLE_GLOG_DLL_DECL void GetExistingTempDirectories(
  1163. std::vector<std::string>* list);
  1164. // Print any fatal message again -- useful to call from signal handler
  1165. // so that the last thing in the output is the fatal message.
  1166. // Thread-hostile, but a race is unlikely.
  1167. GOOGLE_GLOG_DLL_DECL void ReprintFatalMessage();
  1168. // Truncate a log file that may be the append-only output of multiple
  1169. // processes and hence can't simply be renamed/reopened (typically a
  1170. // stdout/stderr). If the file "path" is > "limit" bytes, copy the
  1171. // last "keep" bytes to offset 0 and truncate the rest. Since we could
  1172. // be racing with other writers, this approach has the potential to
  1173. // lose very small amounts of data. For security, only follow symlinks
  1174. // if the path is /proc/self/fd/*
  1175. GOOGLE_GLOG_DLL_DECL void TruncateLogFile(const char *path,
  1176. int64 limit, int64 keep);
  1177. // Truncate stdout and stderr if they are over the value specified by
  1178. // --max_log_size; keep the final 1MB. This function has the same
  1179. // race condition as TruncateLogFile.
  1180. GOOGLE_GLOG_DLL_DECL void TruncateStdoutStderr();
  1181. // Return the string representation of the provided LogSeverity level.
  1182. // Thread-safe.
  1183. GOOGLE_GLOG_DLL_DECL const char* GetLogSeverityName(LogSeverity severity);
  1184. // ---------------------------------------------------------------------
  1185. // Implementation details that are not useful to most clients
  1186. // ---------------------------------------------------------------------
  1187. // A Logger is the interface used by logging modules to emit entries
  1188. // to a log. A typical implementation will dump formatted data to a
  1189. // sequence of files. We also provide interfaces that will forward
  1190. // the data to another thread so that the invoker never blocks.
  1191. // Implementations should be thread-safe since the logging system
  1192. // will write to them from multiple threads.
  1193. namespace base {
  1194. class GOOGLE_GLOG_DLL_DECL Logger {
  1195. public:
  1196. virtual ~Logger();
  1197. // Writes "message[0,message_len-1]" corresponding to an event that
  1198. // occurred at "timestamp". If "force_flush" is true, the log file
  1199. // is flushed immediately.
  1200. //
  1201. // The input message has already been formatted as deemed
  1202. // appropriate by the higher level logging facility. For example,
  1203. // textual log messages already contain timestamps, and the
  1204. // file:linenumber header.
  1205. virtual void Write(bool force_flush,
  1206. time_t timestamp,
  1207. const char* message,
  1208. int message_len) = 0;
  1209. // Flush any buffered messages
  1210. virtual void Flush() = 0;
  1211. // Get the current LOG file size.
  1212. // The returned value is approximate since some
  1213. // logged data may not have been flushed to disk yet.
  1214. virtual uint32 LogSize() = 0;
  1215. };
  1216. // Get the logger for the specified severity level. The logger
  1217. // remains the property of the logging module and should not be
  1218. // deleted by the caller. Thread-safe.
  1219. extern GOOGLE_GLOG_DLL_DECL Logger* GetLogger(LogSeverity level);
  1220. // Set the logger for the specified severity level. The logger
  1221. // becomes the property of the logging module and should not
  1222. // be deleted by the caller. Thread-safe.
  1223. extern GOOGLE_GLOG_DLL_DECL void SetLogger(LogSeverity level, Logger* logger);
  1224. }
  1225. // glibc has traditionally implemented two incompatible versions of
  1226. // strerror_r(). There is a poorly defined convention for picking the
  1227. // version that we want, but it is not clear whether it even works with
  1228. // all versions of glibc.
  1229. // So, instead, we provide this wrapper that automatically detects the
  1230. // version that is in use, and then implements POSIX semantics.
  1231. // N.B. In addition to what POSIX says, we also guarantee that "buf" will
  1232. // be set to an empty string, if this function failed. This means, in most
  1233. // cases, you do not need to check the error code and you can directly
  1234. // use the value of "buf". It will never have an undefined value.
  1235. GOOGLE_GLOG_DLL_DECL int posix_strerror_r(int err, char *buf, size_t len);
  1236. // A class for which we define operator<<, which does nothing.
  1237. class GOOGLE_GLOG_DLL_DECL NullStream : public LogMessage::LogStream {
  1238. public:
  1239. // Initialize the LogStream so the messages can be written somewhere
  1240. // (they'll never be actually displayed). This will be needed if a
  1241. // NullStream& is implicitly converted to LogStream&, in which case
  1242. // the overloaded NullStream::operator<< will not be invoked.
  1243. NullStream() : LogMessage::LogStream(message_buffer_, 1, 0) { }
  1244. NullStream(const char* /*file*/, int /*line*/,
  1245. const CheckOpString& /*result*/) :
  1246. LogMessage::LogStream(message_buffer_, 1, 0) { }
  1247. NullStream &stream() { return *this; }
  1248. private:
  1249. // A very short buffer for messages (which we discard anyway). This
  1250. // will be needed if NullStream& converted to LogStream& (e.g. as a
  1251. // result of a conditional expression).
  1252. char message_buffer_[2];
  1253. };
  1254. // Do nothing. This operator is inline, allowing the message to be
  1255. // compiled away. The message will not be compiled away if we do
  1256. // something like (flag ? LOG(INFO) : LOG(ERROR)) << message; when
  1257. // SKIP_LOG=WARNING. In those cases, NullStream will be implicitly
  1258. // converted to LogStream and the message will be computed and then
  1259. // quietly discarded.
  1260. template<class T>
  1261. inline NullStream& operator<<(NullStream &str, const T &value) { return str; }
  1262. // Similar to NullStream, but aborts the program (without stack
  1263. // trace), like LogMessageFatal.
  1264. class GOOGLE_GLOG_DLL_DECL NullStreamFatal : public NullStream {
  1265. public:
  1266. NullStreamFatal() { }
  1267. NullStreamFatal(const char* file, int line, const CheckOpString& result) :
  1268. NullStream(file, line, result) { }
  1269. ~NullStreamFatal() { _exit(1); }
  1270. };
  1271. // Install a signal handler that will dump signal information and a stack
  1272. // trace when the program crashes on certain signals. We'll install the
  1273. // signal handler for the following signals.
  1274. //
  1275. // SIGSEGV, SIGILL, SIGFPE, SIGABRT, SIGBUS, and SIGTERM.
  1276. //
  1277. // By default, the signal handler will write the failure dump to the
  1278. // standard error. You can customize the destination by installing your
  1279. // own writer function by InstallFailureWriter() below.
  1280. //
  1281. // Note on threading:
  1282. //
  1283. // The function should be called before threads are created, if you want
  1284. // to use the failure signal handler for all threads. The stack trace
  1285. // will be shown only for the thread that receives the signal. In other
  1286. // words, stack traces of other threads won't be shown.
  1287. GOOGLE_GLOG_DLL_DECL void InstallFailureSignalHandler();
  1288. // Installs a function that is used for writing the failure dump. "data"
  1289. // is the pointer to the beginning of a message to be written, and "size"
  1290. // is the size of the message. You should not expect the data is
  1291. // terminated with '\0'.
  1292. GOOGLE_GLOG_DLL_DECL void InstallFailureWriter(
  1293. void (*writer)(const char* data, int size));
  1294. }
  1295. #endif // _LOGGING_H_