logging.h 63 KB

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