2 // Copyright (C) 1999 and onwards Google, Inc.
6 // This file contains #include information about logging-related stuff.
7 // Pretty much everybody needs to #include this file so that they can
8 // log various happenings.
28 // We care a lot about number of bits things take up. Unfortunately,
29 // systems define their bit-specific ints in a lot of different ways.
30 // We use our own way, and have a typedef to get there.
31 // Note: these commands below may look like "#if 1" or "#if 0", but
32 // that's because they were constructed that way at ./configure time.
33 // Look at logging.h.in to see how they're calculated (based on your config).
34 #if @ac_cv_have_stdint_h@
35 #include <stdint.h> // the normal place uint16_t is defined
37 #if @ac_cv_have_systypes_h@
38 #include <sys/types.h> // the normal place u_int16_t is defined
40 #if @ac_cv_have_inttypes_h@
41 #include <inttypes.h> // a third place for uint16_t or u_int16_t
44 #if @ac_cv_have_libgflags@
45 #include <gflags/gflags.h>
48 @ac_google_start_namespace@
50 #if @ac_cv_have_uint16_t@ // the C99 format
51 typedef int32_t int32;
52 typedef uint32_t uint32;
53 typedef int64_t int64;
54 typedef uint64_t uint64;
55 #elif @ac_cv_have_u_int16_t@ // the BSD format
56 typedef int32_t int32;
57 typedef u_int32_t uint32;
58 typedef int64_t int64;
59 typedef u_int64_t uint64;
60 #elif @ac_cv_have___uint16@ // the windows (vc7) format
61 typedef __int32 int32;
62 typedef __uint32 uint32;
63 typedef __int64 int64;
64 typedef __uint64 uint64;
66 #error Do not know how to define a 32-bit integer quantity on your system
69 @ac_google_end_namespace@
71 // The global value of GOOGLE_STRIP_LOG. All the messages logged to
72 // LOG(XXX) with severity less than GOOGLE_STRIP_LOG will not be displayed.
73 // If it can be determined at compile time that the message will not be
74 // printed, the statement will be compiled out.
76 // Example: to strip out all INFO and WARNING messages, use the value
77 // of 2 below. To make an exception for WARNING messages from a single
78 // file, add "#define GOOGLE_STRIP_LOG 1" to that file _before_ including
80 #ifndef GOOGLE_STRIP_LOG
81 #define GOOGLE_STRIP_LOG 0
84 // GCC can be told that a certain branch is not likely to be taken (for
85 // instance, a CHECK failure), and use that information in static analysis.
86 // Giving it this information can help it optimize for the common case in
87 // the absence of better information (ie. -fprofile-arcs).
89 #ifndef GOOGLE_PREDICT_BRANCH_NOT_TAKEN
90 #if @ac_cv_have___builtin_expect@
91 #define GOOGLE_PREDICT_BRANCH_NOT_TAKEN(x) (__builtin_expect(x, 0))
93 #define GOOGLE_PREDICT_BRANCH_NOT_TAKEN(x) x
97 // Make a bunch of macros for logging. The way to log things is to stream
98 // things to LOG(<a particular severity level>). E.g.,
100 // LOG(INFO) << "Found " << num_cookies << " cookies";
102 // You can capture log messages in a string, rather than reporting them
105 // vector<string> errors;
106 // LOG_STRING(ERROR, &errors) << "Couldn't parse cookie #" << cookie_num;
108 // This pushes back the new error onto 'errors'; if given a NULL pointer,
109 // it reports the error via LOG(ERROR).
111 // You can also do conditional logging:
113 // LOG_IF(INFO, num_cookies > 10) << "Got lots of cookies";
115 // You can also do occasional logging (log every n'th occurrence of an
118 // LOG_EVERY_N(INFO, 10) << "Got the " << COUNTER << "th cookie";
120 // The above will cause log messages to be output on the 1st, 11th, 21st, ...
121 // times it is executed. Note that the special COUNTER value is used to
122 // identify which repetition is happening.
124 // You can also do occasional conditional logging (log every n'th
125 // occurrence of an event, when condition is satisfied):
127 // LOG_IF_EVERY_N(INFO, (size > 1024), 10) << "Got the " << COUNTER
128 // << "th big cookie";
130 // You can log messages the first N times your code executes a line. E.g.
132 // LOG_FIRST_N(INFO, 20) << "Got the " << COUNTER << "th cookie";
134 // Outputs log messages for the first 20 times it is executed.
136 // Analogous SYSLOG, SYSLOG_IF, and SYSLOG_EVERY_N macros are available.
137 // These log to syslog as well as to the normal logs. If you use these at
138 // all, you need to be aware that syslog can drastically reduce performance,
139 // especially if it is configured for remote logging! Don't use these
140 // unless you fully understand this and have a concrete need to use them.
141 // Even then, try to minimize your use of them.
143 // There are also "debug mode" logging macros like the ones above:
145 // DLOG(INFO) << "Found cookies";
147 // DLOG_IF(INFO, num_cookies > 10) << "Got lots of cookies";
149 // DLOG_EVERY_N(INFO, 10) << "Got the " << COUNTER << "th cookie";
151 // All "debug mode" logging is compiled away to nothing for non-debug mode
156 // LOG_ASSERT(assertion);
157 // DLOG_ASSERT(assertion);
159 // which is syntactic sugar for {,D}LOG_IF(FATAL, assert fails) << assertion;
161 // There are "verbose level" logging macros. They look like
163 // VLOG(1) << "I'm printed when you run the program with --v=1 or more";
164 // VLOG(2) << "I'm printed when you run the program with --v=2 or more";
166 // These always log at the INFO log level (when they log at all).
167 // The verbose logging can also be turned on module-by-module. For instance,
168 // --vmodule=mapreduce=2,file=1,gfs*=3 --v=0
170 // a. VLOG(2) and lower messages to be printed from mapreduce.{h,cc}
171 // b. VLOG(1) and lower messages to be printed from file.{h,cc}
172 // c. VLOG(3) and lower messages to be printed from files prefixed with "gfs"
173 // d. VLOG(0) and lower messages to be printed from elsewhere
175 // The wildcarding functionality shown by (c) supports both '*' (match
176 // 0 or more characters) and '?' (match any single character) wildcards.
178 // There's also VLOG_IS_ON(n) "verbose level" condition macro. To be used as
180 // if (VLOG_IS_ON(2)) {
181 // // do some logging preparation and logging
182 // // that can't be accomplished with just VLOG(2) << ...;
185 // There are also VLOG_IF, VLOG_EVERY_N and VLOG_IF_EVERY_N "verbose level"
186 // condition macros for sample cases, when some extra computation and
187 // preparation for logs is not needed.
188 // VLOG_IF(1, (size > 1024))
189 // << "I'm printed when size is more than 1024 and when you run the "
190 // "program with --v=1 or more";
191 // VLOG_EVERY_N(1, 10)
192 // << "I'm printed every 10th occurrence, and when you run the program "
193 // "with --v=1 or more. Present occurence is " << COUNTER;
194 // VLOG_IF_EVERY_N(1, (size > 1024), 10)
195 // << "I'm printed on every 10th occurence of case when size is more "
196 // " than 1024, when you run the program with --v=1 or more. ";
197 // "Present occurence is " << COUNTER;
199 // The supported severity levels for macros that allow you to specify one
200 // are (in increasing order of severity) INFO, WARNING, ERROR, and FATAL.
201 // Note that messages of a given severity are logged not only in the
202 // logfile for that severity, but also in all logfiles of lower severity.
203 // E.g., a message of severity FATAL will be logged to the logfiles of
204 // severity FATAL, ERROR, WARNING, and INFO.
206 // There is also the special severity of DFATAL, which logs FATAL in
207 // debug mode, ERROR in normal mode.
209 // Very important: logging a message at the FATAL severity level causes
210 // the program to terminate (after the message is logged).
212 // Unless otherwise specified, logs will be written to the filename
213 // "<program name>.<hostname>.<user name>.log.<severity level>.", followed
214 // by the date, time, and pid (you can't prevent the date, time, and pid
215 // from being in the filename).
217 // The logging code takes two flags:
218 // --v=# set the verbose level
219 // --logtostderr log all the messages to stderr instead of to logfiles
221 #ifndef DECLARE_VARIABLE
222 #define MUST_UNDEF_GFLAGS_DECLARE_MACROS
223 #define DECLARE_VARIABLE(type, name, tn) \
224 namespace FLAG__namespace_do_not_use_directly_use_DECLARE_##tn##_instead { \
225 extern type FLAGS_##name; \
227 using FLAG__namespace_do_not_use_directly_use_DECLARE_##tn##_instead::FLAGS_##name
229 // bool specialization
230 #define DECLARE_bool(name) \
231 DECLARE_VARIABLE(bool, name, bool)
233 // int32 specialization
234 #define DECLARE_int32(name) \
235 DECLARE_VARIABLE(@ac_google_namespace@::int32, name, int32)
237 // Special case for string, because we have to specify the namespace
238 // std::string, which doesn't play nicely with our FLAG__namespace hackery.
239 #define DECLARE_string(name) \
240 namespace FLAG__namespace_do_not_use_directly_use_DECLARE_string_instead { \
241 extern std::string FLAGS_##name; \
243 using FLAG__namespace_do_not_use_directly_use_DECLARE_string_instead::FLAGS_##name
246 // Set whether log messages go to stderr instead of logfiles
247 DECLARE_bool(logtostderr);
249 // Set how important a log message should be to avoid buffering
250 DECLARE_int32(logbuflevel);
252 // Log suppression level: messages logged at a lower level than this
254 DECLARE_int32(minloglevel);
256 // If specified, logfiles are written into this directory instead of the
257 // default logging directory.
258 DECLARE_string(log_dir);
260 DECLARE_int32(v); // in vlog_is_on.cc
262 DECLARE_int32(stderrthreshold);
263 DECLARE_bool(alsologtostderr);
265 #ifdef MUST_UNDEF_GFLAGS_DECLARE_MACROS
266 #undef MUST_UNDEF_GFLAGS_DECLARE_MACROS
267 #undef DECLARE_VARIABLE
270 #undef DECLARE_string
273 // Log messages below the GOOGLE_STRIP_LOG level will be compiled away for
274 // security reasons. See LOG(severtiy) below.
276 // A few definitions of macros that don't generate much code. Since
277 // LOG(INFO) and its ilk are used all over our code, it's
278 // better to have compact code for these operations.
280 #if 0 >= GOOGLE_STRIP_LOG
281 #define COMPACT_GOOGLE_LOG_INFO @ac_google_namespace@::LogMessage(__FILE__, __LINE__)
283 #define COMPACT_GOOGLE_LOG_INFO @ac_google_namespace@::NullStream()
286 #if 1 >= GOOGLE_STRIP_LOG
287 #define COMPACT_GOOGLE_LOG_WARNING @ac_google_namespace@::LogMessage(__FILE__, __LINE__, @ac_google_namespace@::WARNING)
289 #define COMPACT_GOOGLE_LOG_WARNING @ac_google_namespace@::NullStream()
292 #if 2 >= GOOGLE_STRIP_LOG
293 #define COMPACT_GOOGLE_LOG_ERROR @ac_google_namespace@::LogMessage(__FILE__, __LINE__, @ac_google_namespace@::ERROR)
295 #define COMPACT_GOOGLE_LOG_ERROR @ac_google_namespace@::NullStream()
298 #if 3 >= GOOGLE_STRIP_LOG
299 #define COMPACT_GOOGLE_LOG_FATAL @ac_google_namespace@::LogMessageFatal(__FILE__, __LINE__)
301 #define COMPACT_GOOGLE_LOG_FATAL @ac_google_namespace@::NullStreamFatal()
304 // For DFATAL, we want to use LogMessage (as opposed to
305 // LogMessageFatal), to be consistent with the original behavior.
307 #define COMPACT_GOOGLE_LOG_DFATAL COMPACT_GOOGLE_LOG_ERROR
308 #elif 3 >= GOOGLE_STRIP_LOG
309 #define COMPACT_GOOGLE_LOG_DFATAL @ac_google_namespace@::LogMessage(__FILE__, __LINE__, @ac_google_namespace@::FATAL)
311 #define COMPACT_GOOGLE_LOG_DFATAL @ac_google_namespace@::NullStreamFatal()
314 #define GOOGLE_LOG_INFO(counter) @ac_google_namespace@::LogMessage(__FILE__, __LINE__, @ac_google_namespace@::INFO, counter, &@ac_google_namespace@::LogMessage::SendToLog)
315 #define SYSLOG_INFO(counter) \
316 @ac_google_namespace@::LogMessage(__FILE__, __LINE__, @ac_google_namespace@::INFO, counter, \
317 &@ac_google_namespace@::LogMessage::SendToSyslogAndLog)
318 #define GOOGLE_LOG_WARNING(counter) \
319 @ac_google_namespace@::LogMessage(__FILE__, __LINE__, @ac_google_namespace@::WARNING, counter, \
320 &@ac_google_namespace@::LogMessage::SendToLog)
321 #define SYSLOG_WARNING(counter) \
322 @ac_google_namespace@::LogMessage(__FILE__, __LINE__, @ac_google_namespace@::WARNING, counter, \
323 &@ac_google_namespace@::LogMessage::SendToSyslogAndLog)
324 #define GOOGLE_LOG_ERROR(counter) \
325 @ac_google_namespace@::LogMessage(__FILE__, __LINE__, @ac_google_namespace@::ERROR, counter, \
326 &@ac_google_namespace@::LogMessage::SendToLog)
327 #define SYSLOG_ERROR(counter) \
328 @ac_google_namespace@::LogMessage(__FILE__, __LINE__, @ac_google_namespace@::ERROR, counter, \
329 &@ac_google_namespace@::LogMessage::SendToSyslogAndLog)
330 #define GOOGLE_LOG_FATAL(counter) \
331 @ac_google_namespace@::LogMessage(__FILE__, __LINE__, @ac_google_namespace@::FATAL, counter, \
332 &@ac_google_namespace@::LogMessage::SendToLog)
333 #define SYSLOG_FATAL(counter) \
334 @ac_google_namespace@::LogMessage(__FILE__, __LINE__, @ac_google_namespace@::FATAL, counter, \
335 &@ac_google_namespace@::LogMessage::SendToSyslogAndLog)
336 #define GOOGLE_LOG_DFATAL(counter) \
337 @ac_google_namespace@::LogMessage(__FILE__, __LINE__, @ac_google_namespace@::DFATAL_LEVEL, counter, \
338 &@ac_google_namespace@::LogMessage::SendToLog)
339 #define SYSLOG_DFATAL(counter) \
340 @ac_google_namespace@::LogMessage(__FILE__, __LINE__, @ac_google_namespace@::DFATAL_LEVEL, counter, \
341 &@ac_google_namespace@::LogMessage::SendToSyslogAndLog)
343 #if defined(WIN32) || defined(_WIN32) || defined(__WIN32__) || defined(__CYGWIN__) || defined(__CYGWIN32__)
344 // A very useful logging macro to log windows errors:
345 #define LOG_SYSRESULT(result) \
346 if (FAILED(result)) { \
347 LPTSTR message = NULL; \
348 LPTSTR msg = reinterpret_cast<LPTSTR>(&message); \
349 DWORD message_length = FormatMessage(FORMAT_MESSAGE_ALLOCATE_BUFFER | \
350 FORMAT_MESSAGE_FROM_SYSTEM, \
351 0, result, 0, msg, 100, NULL); \
352 if (message_length > 0) { \
353 @ac_google_namespace@::LogMessage(__FILE__, __LINE__, ERROR, 0, \
354 &@ac_google_namespace@::LogMessage::SendToLog).stream() << message; \
355 LocalFree(message); \
360 // We use the preprocessor's merging operator, "##", so that, e.g.,
361 // LOG(INFO) becomes the token GOOGLE_LOG_INFO. There's some funny
362 // subtle difference between ostream member streaming functions (e.g.,
363 // ostream::operator<<(int) and ostream non-member streaming functions
364 // (e.g., ::operator<<(ostream&, string&): it turns out that it's
365 // impossible to stream something like a string directly to an unnamed
366 // ostream. We employ a neat hack by calling the stream() member
367 // function of LogMessage which seems to avoid the problem.
368 #define LOG(severity) COMPACT_GOOGLE_LOG_ ## severity.stream()
369 #define SYSLOG(severity) SYSLOG_ ## severity(0).stream()
371 @ac_google_start_namespace@
373 // They need the definitions of integer types.
374 #include "glog/log_severity.h"
375 #include "glog/vlog_is_on.h"
377 // Initialize google's logging library. You will see the program name
378 // specified by argv0 in log outputs.
379 void InitGoogleLogging(const char* argv0);
381 // Install a function which will be called after LOG(FATAL).
382 void InstallFailureFunction(void (*fail_func)());
384 class LogSink; // defined below
386 // If a non-NULL sink pointer is given, we push this message to that sink.
387 // We then do normal LOG(severity) logging as well.
388 // This is useful for capturing messages and passing/storing them
389 // somewhere more specific than the global log of the process.
392 // LogSeverity severity;
393 // The cast is to disambiguate NULL arguments.
394 #define LOG_TO_SINK(sink, severity) \
395 @ac_google_namespace@::LogMessage(__FILE__, __LINE__, @ac_google_namespace@::severity, \
396 static_cast<@ac_google_namespace@::LogSink*>(sink)).stream()
398 // If a non-NULL pointer is given, we push the message onto the end
399 // of a vector of strings; otherwise, we report it with LOG(severity).
400 // This is handy for capturing messages and perhaps passing them back
401 // to the caller, rather than reporting them immediately.
403 // LogSeverity severity;
404 // vector<string> *outvec;
405 // The cast is to disambiguate NULL arguments.
406 #define LOG_STRING(severity, outvec) \
407 @ac_google_namespace@::LogMessage(__FILE__, __LINE__, @ac_google_namespace@::severity, \
408 static_cast<std::vector<std::string>*>(outvec)).stream()
410 #define LOG_IF(severity, condition) \
411 !(condition) ? (void) 0 : @ac_google_namespace@::LogMessageVoidify() & LOG(severity)
412 #define SYSLOG_IF(severity, condition) \
413 !(condition) ? (void) 0 : @ac_google_namespace@::LogMessageVoidify() & SYSLOG(severity)
415 #define LOG_ASSERT(condition) \
416 LOG_IF(FATAL, !(condition)) << "Assert failed: " #condition
417 #define SYSLOG_ASSERT(condition) \
418 SYSLOG_IF(FATAL, !(condition)) << "Assert failed: " #condition
420 // CHECK dies with a fatal error if condition is not true. It is *not*
421 // controlled by NDEBUG, so the check will be executed regardless of
422 // compilation mode. Therefore, it is safe to do things like:
423 // CHECK(fp->Write(x) == 4)
424 #define CHECK(condition) \
425 LOG_IF(FATAL, GOOGLE_PREDICT_BRANCH_NOT_TAKEN(!(condition))) \
426 << "Check failed: " #condition " "
428 // A container for a string pointer which can be evaluated to a bool -
429 // true iff the pointer is NULL.
430 struct CheckOpString {
431 CheckOpString(std::string* str) : str_(str) { }
432 // No destructor: if str_ is non-NULL, we're about to LOG(FATAL),
433 // so there's no point in cleaning up str_.
434 operator bool() const {
435 return GOOGLE_PREDICT_BRANCH_NOT_TAKEN(str_ != NULL);
440 // Function is overloaded for integral types to allow static const
441 // integrals declared in classes and not defined to be used as arguments to
442 // CHECK* macros. It's not encouraged though.
444 inline const T& GetReferenceableValue(const T& t) { return t; }
445 inline char GetReferenceableValue(char t) { return t; }
446 inline unsigned char GetReferenceableValue(unsigned char t) { return t; }
447 inline signed char GetReferenceableValue(signed char t) { return t; }
448 inline short GetReferenceableValue(short t) { return t; }
449 inline unsigned short GetReferenceableValue(unsigned short t) { return t; }
450 inline int GetReferenceableValue(int t) { return t; }
451 inline unsigned int GetReferenceableValue(unsigned int t) { return t; }
452 inline long GetReferenceableValue(long t) { return t; }
453 inline unsigned long GetReferenceableValue(unsigned long t) { return t; }
454 inline long long GetReferenceableValue(long long t) { return t; }
455 inline unsigned long long GetReferenceableValue(unsigned long long t) {
459 // This is a dummy class to define the following operator.
460 struct DummyClassToDefineOperator {};
462 @ac_google_end_namespace@
464 // Define global operator<< to declare using ::operator<<.
465 // This declaration will allow use to use CHECK macros for user
466 // defined classes which have operator<< (e.g., stl_logging.h).
467 inline std::ostream& operator<<(
468 std::ostream& out, const google::DummyClassToDefineOperator& dummy) {
472 @ac_google_start_namespace@
474 // Build the error message string.
475 template<class t1, class t2>
476 std::string* MakeCheckOpString(const t1& v1, const t2& v2, const char* names) {
477 // It means that we cannot use stl_logging if compiler doesn't
478 // support using expression for operator.
479 // TODO(hamaji): Figure out a way to fix.
480 #if @ac_cv_cxx_using_operator@
484 ss << names << " (" << v1 << " vs. " << v2 << ")";
485 return new std::string(ss.str(), ss.pcount());
488 // Helper functions for CHECK_OP macro.
489 // The (int, int) specialization works around the issue that the compiler
490 // will not instantiate the template version of the function on values of
491 // unnamed enum type - see comment below.
492 #define DEFINE_CHECK_OP_IMPL(name, op) \
493 template <class t1, class t2> \
494 inline std::string* Check##name##Impl(const t1& v1, const t2& v2, \
495 const char* names) { \
496 if (v1 op v2) return NULL; \
497 else return MakeCheckOpString(v1, v2, names); \
499 inline std::string* Check##name##Impl(int v1, int v2, const char* names) { \
500 return Check##name##Impl<int, int>(v1, v2, names); \
503 // Use _EQ, _NE, _LE, etc. in case the file including base/logging.h
504 // provides its own #defines for the simpler names EQ, NE, LE, etc.
505 // This happens if, for example, those are used as token names in a
507 DEFINE_CHECK_OP_IMPL(_EQ, ==)
508 DEFINE_CHECK_OP_IMPL(_NE, !=)
509 DEFINE_CHECK_OP_IMPL(_LE, <=)
510 DEFINE_CHECK_OP_IMPL(_LT, < )
511 DEFINE_CHECK_OP_IMPL(_GE, >=)
512 DEFINE_CHECK_OP_IMPL(_GT, > )
513 #undef DEFINE_CHECK_OP_IMPL
515 // Helper macro for binary operators.
516 // Don't use this macro directly in your code, use CHECK_EQ et al below.
518 #if defined(STATIC_ANALYSIS)
519 // Only for static analysis tool to know that it is equivalent to assert
520 #define CHECK_OP_LOG(name, op, val1, val2, log) CHECK((val1) op (val2))
521 #elif !defined(NDEBUG)
522 // In debug mode, avoid constructing CheckOpStrings if possible,
523 // to reduce the overhead of CHECK statments by 2x.
524 // Real DCHECK-heavy tests have seen 1.5x speedups.
526 // The meaning of "string" might be different between now and
527 // when this macro gets invoked (e.g., if someone is experimenting
528 // with other string implementations that get defined after this
529 // file is included). Save the current meaning now and use it
531 typedef std::string _Check_string;
532 #define CHECK_OP_LOG(name, op, val1, val2, log) \
533 while (@ac_google_namespace@::_Check_string* _result = \
534 @ac_google_namespace@::Check##name##Impl((val1), (val2), #val1 " " #op " " #val2)) \
535 log(__FILE__, __LINE__, @ac_google_namespace@::CheckOpString(_result)).stream()
537 // In optimized mode, use CheckOpString to hint to compiler that
538 // the while condition is unlikely.
539 #define CHECK_OP_LOG(name, op, val1, val2, log) \
540 while (@ac_google_namespace@::CheckOpString _result = \
541 @ac_google_namespace@::Check##name##Impl(GetReferenceableValue(val1), \
542 GetReferenceableValue(val2), \
543 #val1 " " #op " " #val2)) \
544 log(__FILE__, __LINE__, _result).stream()
545 #endif // STATIC_ANALYSIS, !NDEBUG
547 #define CHECK_OP(name, op, val1, val2) \
548 CHECK_OP_LOG(name, op, val1, val2, @ac_google_namespace@::LogMessageFatal)
550 // Equality/Inequality checks - compare two values, and log a FATAL message
551 // including the two values when the result is not as expected. The values
552 // must have operator<<(ostream, ...) defined.
554 // You may append to the error message like so:
555 // CHECK_NE(1, 2) << ": The world must be ending!";
557 // We are very careful to ensure that each argument is evaluated exactly
558 // once, and that anything which is legal to pass as a function argument is
559 // legal here. In particular, the arguments may be temporary expressions
560 // which will end up being destroyed at the end of the apparent statement,
562 // CHECK_EQ(string("abc")[1], 'b');
564 // WARNING: These don't compile correctly if one of the arguments is a pointer
565 // and the other is NULL. To work around this, simply static_cast NULL to the
566 // type of the desired pointer.
568 #define CHECK_EQ(val1, val2) CHECK_OP(_EQ, ==, val1, val2)
569 #define CHECK_NE(val1, val2) CHECK_OP(_NE, !=, val1, val2)
570 #define CHECK_LE(val1, val2) CHECK_OP(_LE, <=, val1, val2)
571 #define CHECK_LT(val1, val2) CHECK_OP(_LT, < , val1, val2)
572 #define CHECK_GE(val1, val2) CHECK_OP(_GE, >=, val1, val2)
573 #define CHECK_GT(val1, val2) CHECK_OP(_GT, > , val1, val2)
575 // Check that the input is non NULL. This very useful in constructor
576 // initializer lists.
578 #define CHECK_NOTNULL(val) \
579 @ac_google_namespace@::CheckNotNull(__FILE__, __LINE__, "'" #val "' Must be non NULL", (val))
581 // Helper functions for string comparisons.
582 // To avoid bloat, the definitions are in logging.cc.
583 #define DECLARE_CHECK_STROP_IMPL(func, expected) \
584 std::string* Check##func##expected##Impl(const char* s1, const char* s2, \
586 DECLARE_CHECK_STROP_IMPL(strcmp, true)
587 DECLARE_CHECK_STROP_IMPL(strcmp, false)
588 DECLARE_CHECK_STROP_IMPL(strcasecmp, true)
589 DECLARE_CHECK_STROP_IMPL(strcasecmp, false)
590 #undef DECLARE_CHECK_STROP_IMPL
592 // Helper macro for string comparisons.
593 // Don't use this macro directly in your code, use CHECK_STREQ et al below.
594 #define CHECK_STROP(func, op, expected, s1, s2) \
595 while (@ac_google_namespace@::CheckOpString _result = \
596 @ac_google_namespace@::Check##func##expected##Impl((s1), (s2), \
597 #s1 " " #op " " #s2)) \
598 LOG(FATAL) << *_result.str_
601 // String (char*) equality/inequality checks.
602 // CASE versions are case-insensitive.
604 // Note that "s1" and "s2" may be temporary strings which are destroyed
605 // by the compiler at the end of the current "full expression"
606 // (e.g. CHECK_STREQ(Foo().c_str(), Bar().c_str())).
608 #define CHECK_STREQ(s1, s2) CHECK_STROP(strcmp, ==, true, s1, s2)
609 #define CHECK_STRNE(s1, s2) CHECK_STROP(strcmp, !=, false, s1, s2)
610 #define CHECK_STRCASEEQ(s1, s2) CHECK_STROP(strcasecmp, ==, true, s1, s2)
611 #define CHECK_STRCASENE(s1, s2) CHECK_STROP(strcasecmp, !=, false, s1, s2)
613 #define CHECK_INDEX(I,A) CHECK(I < (sizeof(A)/sizeof(A[0])))
614 #define CHECK_BOUND(B,A) CHECK(B <= (sizeof(A)/sizeof(A[0])))
616 #define CHECK_DOUBLE_EQ(val1, val2) \
618 CHECK_LE((val1), (val2)+0.000000000000001L); \
619 CHECK_GE((val1), (val2)-0.000000000000001L); \
622 #define CHECK_NEAR(val1, val2, margin) \
624 CHECK_LE((val1), (val2)+(margin)); \
625 CHECK_GE((val1), (val2)-(margin)); \
628 // perror()..googly style!
630 // PLOG() and PLOG_IF() and PCHECK() behave exactly like their LOG* and
631 // CHECK equivalents with the addition that they postpend a description
632 // of the current state of errno to their output lines.
634 #define PLOG(severity) GOOGLE_PLOG(severity, 0).stream()
636 #define GOOGLE_PLOG(severity, counter) \
637 @ac_google_namespace@::ErrnoLogMessage( \
638 __FILE__, __LINE__, @ac_google_namespace@::severity, counter, \
639 &@ac_google_namespace@::LogMessage::SendToLog)
641 #define PLOG_IF(severity, condition) \
642 !(condition) ? (void) 0 : @ac_google_namespace@::LogMessageVoidify() & PLOG(severity)
644 // A CHECK() macro that postpends errno if the condition is false. E.g.
646 // if (poll(fds, nfds, timeout) == -1) { PCHECK(errno == EINTR); ... }
647 #define PCHECK(condition) \
648 PLOG_IF(FATAL, GOOGLE_PREDICT_BRANCH_NOT_TAKEN(!(condition))) \
649 << "Check failed: " #condition " "
651 // A CHECK() macro that lets you assert the success of a function that
652 // returns -1 and sets errno in case of an error. E.g.
654 // CHECK_ERR(mkdir(path, 0700));
658 // int fd = open(filename, flags); CHECK_ERR(fd) << ": open " << filename;
659 #define CHECK_ERR(invocation) \
660 PLOG_IF(FATAL, GOOGLE_PREDICT_BRANCH_NOT_TAKEN((invocation) == -1)) \
663 // Use macro expansion to create, for each use of LOG_EVERY_N(), static
664 // variables with the __LINE__ expansion as part of the variable name.
665 #define LOG_EVERY_N_VARNAME(base, line) LOG_EVERY_N_VARNAME_CONCAT(base, line)
666 #define LOG_EVERY_N_VARNAME_CONCAT(base, line) base ## line
668 #define LOG_OCCURRENCES LOG_EVERY_N_VARNAME(occurrences_, __LINE__)
669 #define LOG_OCCURRENCES_MOD_N LOG_EVERY_N_VARNAME(occurrences_mod_n_, __LINE__)
671 #define SOME_KIND_OF_LOG_EVERY_N(severity, n, what_to_do) \
672 static int LOG_OCCURRENCES = 0, LOG_OCCURRENCES_MOD_N = 0; \
674 if (++LOG_OCCURRENCES_MOD_N > n) LOG_OCCURRENCES_MOD_N -= n; \
675 if (LOG_OCCURRENCES_MOD_N == 1) \
676 @ac_google_namespace@::LogMessage( \
677 __FILE__, __LINE__, @ac_google_namespace@::severity, LOG_OCCURRENCES, \
678 &what_to_do).stream()
680 #define SOME_KIND_OF_LOG_IF_EVERY_N(severity, condition, n, what_to_do) \
681 static int LOG_OCCURRENCES = 0, LOG_OCCURRENCES_MOD_N = 0; \
684 ((LOG_OCCURRENCES_MOD_N=(LOG_OCCURRENCES_MOD_N + 1) % n) == (1 % n))) \
685 @ac_google_namespace@::LogMessage( \
686 __FILE__, __LINE__, @ac_google_namespace@::severity, LOG_OCCURRENCES, \
687 &what_to_do).stream()
689 #define SOME_KIND_OF_PLOG_EVERY_N(severity, n, what_to_do) \
690 static int LOG_OCCURRENCES = 0, LOG_OCCURRENCES_MOD_N = 0; \
692 if (++LOG_OCCURRENCES_MOD_N > n) LOG_OCCURRENCES_MOD_N -= n; \
693 if (LOG_OCCURRENCES_MOD_N == 1) \
694 @ac_google_namespace@::ErrnoLogMessage( \
695 __FILE__, __LINE__, @ac_google_namespace@::severity, LOG_OCCURRENCES, \
696 &what_to_do).stream()
698 #define SOME_KIND_OF_LOG_FIRST_N(severity, n, what_to_do) \
699 static int LOG_OCCURRENCES = 0; \
700 if (LOG_OCCURRENCES <= n) \
702 if (LOG_OCCURRENCES <= n) \
703 @ac_google_namespace@::LogMessage( \
704 __FILE__, __LINE__, @ac_google_namespace@::severity, LOG_OCCURRENCES, \
705 &what_to_do).stream()
707 #define LOG_EVERY_N(severity, n) \
708 SOME_KIND_OF_LOG_EVERY_N(severity, (n), @ac_google_namespace@::LogMessage::SendToLog)
710 #define SYSLOG_EVERY_N(severity, n) \
711 SOME_KIND_OF_LOG_EVERY_N(severity, (n), @ac_google_namespace@::LogMessage::SendToSyslogAndLog)
713 #define PLOG_EVERY_N(severity, n) \
714 SOME_KIND_OF_PLOG_EVERY_N(severity, (n), @ac_google_namespace@::LogMessage::SendToLog)
716 #define LOG_FIRST_N(severity, n) \
717 SOME_KIND_OF_LOG_FIRST_N(severity, (n), @ac_google_namespace@::LogMessage::SendToLog)
719 #define LOG_IF_EVERY_N(severity, condition, n) \
720 SOME_KIND_OF_LOG_IF_EVERY_N(severity, (condition), (n), @ac_google_namespace@::LogMessage::SendToLog)
722 // We want the special COUNTER value available for LOG_EVERY_X()'ed messages
723 enum PRIVATE_Counter {COUNTER};
726 // Plus some debug-logging macros that get compiled to nothing for production
730 #define DLOG(severity) LOG(severity)
731 #define DLOG_IF(severity, condition) LOG_IF(severity, condition)
732 #define DLOG_EVERY_N(severity, n) LOG_EVERY_N(severity, n)
733 #define DLOG_IF_EVERY_N(severity, condition, n) \
734 LOG_IF_EVERY_N(severity, condition, n)
735 #define DLOG_ASSERT(condition) LOG_ASSERT(condition)
737 // debug-only checking. not executed in NDEBUG mode.
738 #define DCHECK(condition) CHECK(condition)
739 #define DCHECK_EQ(val1, val2) CHECK_EQ(val1, val2)
740 #define DCHECK_NE(val1, val2) CHECK_NE(val1, val2)
741 #define DCHECK_LE(val1, val2) CHECK_LE(val1, val2)
742 #define DCHECK_LT(val1, val2) CHECK_LT(val1, val2)
743 #define DCHECK_GE(val1, val2) CHECK_GE(val1, val2)
744 #define DCHECK_GT(val1, val2) CHECK_GT(val1, val2)
745 #define DCHECK_STREQ(str1, str2) CHECK_STREQ(str1, str2)
746 #define DCHECK_STRCASEEQ(str1, str2) CHECK_STRCASEEQ(str1, str2)
747 #define DCHECK_STRNE(str1, str2) CHECK_STRNE(str1, str2)
748 #define DCHECK_STRCASENE(str1, str2) CHECK_STRCASENE(str1, str2)
752 #define DLOG(severity) \
753 true ? (void) 0 : @ac_google_namespace@::LogMessageVoidify() & LOG(severity)
755 #define DLOG_IF(severity, condition) \
756 (true || !(condition)) ? (void) 0 : @ac_google_namespace@::LogMessageVoidify() & LOG(severity)
758 #define DLOG_EVERY_N(severity, n) \
759 true ? (void) 0 : @ac_google_namespace@::LogMessageVoidify() & LOG(severity)
761 #define DLOG_IF_EVERY_N(severity, condition, n) \
762 (true || !(condition))? (void) 0 : @ac_google_namespace@::LogMessageVoidify() & LOG(severity)
764 #define DLOG_ASSERT(condition) \
765 true ? (void) 0 : LOG_ASSERT(condition)
767 #define DCHECK(condition) \
771 #define DCHECK_EQ(val1, val2) \
775 #define DCHECK_NE(val1, val2) \
779 #define DCHECK_LE(val1, val2) \
783 #define DCHECK_LT(val1, val2) \
787 #define DCHECK_GE(val1, val2) \
791 #define DCHECK_GT(val1, val2) \
795 #define DCHECK_STREQ(str1, str2) \
797 CHECK_STREQ(str1, str2)
799 #define DCHECK_STRCASEEQ(str1, str2) \
801 CHECK_STRCASEEQ(str1, str2)
803 #define DCHECK_STRNE(str1, str2) \
805 CHECK_STRNE(str1, str2)
807 #define DCHECK_STRCASENE(str1, str2) \
809 CHECK_STRCASENE(str1, str2)
814 // Log only in verbose mode.
816 #define VLOG(verboselevel) LOG_IF(INFO, VLOG_IS_ON(verboselevel))
818 #define VLOG_IF(verboselevel, condition) \
819 LOG_IF(INFO, (condition) && VLOG_IS_ON(verboselevel))
821 #define VLOG_EVERY_N(verboselevel, n) \
822 LOG_IF_EVERY_N(INFO, VLOG_IS_ON(verboselevel), n)
824 #define VLOG_IF_EVERY_N(verboselevel, condition, n) \
825 LOG_IF_EVERY_N(INFO, (condition) && VLOG_IS_ON(verboselevel), n)
828 // This class more or less represents a particular log message. You
829 // create an instance of LogMessage and then stream stuff to it.
830 // When you finish streaming to it, ~LogMessage is called and the
831 // full message gets streamed to the appropriate destination.
833 // You shouldn't actually use LogMessage's constructor to log things,
834 // though. You should use the LOG() macro (and variants thereof)
839 // Passing kNoLogPrefix for the line number disables the
840 // log-message prefix. Useful for using the LogMessage
841 // infrastructure as a printing utility. See also the --log_prefix
842 // flag for controlling the log-message prefix on an
843 // application-wide basis.
847 class LogStream : public std::ostrstream {
849 LogStream(char *buf, int len, int ctr)
850 : ostrstream(buf, len),
855 int ctr() const { return ctr_; }
856 void set_ctr(int ctr) { ctr_ = ctr; }
857 LogStream* self() const { return self_; }
860 int ctr_; // Counter hack (for the LOG_EVERY_X() macro)
861 LogStream *self_; // Consistency check hack
865 // icc 8 requires this typedef to avoid an internal compiler error.
866 typedef void (LogMessage::*SendMethod)();
868 LogMessage(const char* file, int line, LogSeverity severity, int ctr,
869 SendMethod send_method);
871 // Two special constructors that generate reduced amounts of code at
872 // LOG call sites for common cases.
874 // Used for LOG(INFO): Implied are:
875 // severity = INFO, ctr = 0, send_method = &LogMessage::SendToLog.
877 // Using this constructor instead of the more complex constructor above
878 // saves 19 bytes per call site.
879 LogMessage(const char* file, int line);
881 // Used for LOG(severity) where severity != INFO. Implied
882 // are: ctr = 0, send_method = &LogMessage::SendToLog
884 // Using this constructor instead of the more complex constructor above
885 // saves 17 bytes per call site.
886 LogMessage(const char* file, int line, LogSeverity severity);
888 // Constructor to also log this message to a specified sink (if not NULL).
889 // Implied are: ctr = 0, send_method = &LogMessage::SendToSinkAndLog.
890 LogMessage(const char* file, int line, LogSeverity severity, LogSink* sink);
892 // Constructor where we also give a vector<string> pointer
893 // for storing the messages (if the pointer is not NULL).
894 // Implied are: ctr = 0, send_method = &LogMessage::SaveOrSendToLog.
895 LogMessage(const char* file, int line, LogSeverity severity,
896 std::vector<std::string>* outvec);
898 // A special constructor used for check failures
899 LogMessage(const char* file, int line, const CheckOpString& result);
903 // Flush a buffered message to the sink set in the constructor. Always
904 // called by the destructor, it may also be called from elsewhere if
905 // needed. Only the first call is actioned; any later ones are ignored.
908 // An arbitrary limit on the length of a single log message. This
909 // is so that streaming can be done more efficiently.
910 static const size_t kMaxLogMessageLen;
912 // Theses should not be called directly outside of logging.*,
913 // only passed as SendMethod arguments to other LogMessage methods:
914 void SendToLog(); // Actually dispatch to the logs
915 void SendToSyslogAndLog(); // Actually dispatch to syslog and the logs
917 // Call abort() or similar to perform LOG(FATAL) crash.
918 static void Fail() @ac_cv___attribute___noreturn@;
920 std::ostream& stream() { return data_->stream_; }
922 int preserved_errno() const { return data_->preserved_errno_; }
924 // Must be called without the log_mutex held. (L < log_mutex)
925 static int64 num_messages(int severity);
929 // Fully internal SendMethod cases:
930 void SendToSinkAndLog(); // Send to sink if provided and dispatch to the logs
931 void SaveOrSendToLog(); // Save to stringvec if provided, else to logs
933 struct LogMessageData;
935 void Init(const char* file, int line, LogSeverity severity,
936 void (LogMessage::*send_method)());
938 LogMessageData* GetMessageData(int preserved_errno, LogSeverity, int ctr);
940 // Counts of messages sent at each priority:
941 static int64 num_messages_[NUM_SEVERITIES]; // under log_mutex
943 static LogMessageData fatal_message_data_;
945 // We keep the data in a separate struct so that each instance of
946 // LogMessage uses less stack space.
947 struct LogMessageData {
948 // ORDER DEPENDENCY: preserved_errno_ comes before buf_ comes before
949 // message_text_ comes before stream_
950 int preserved_errno_; // preserved errno
952 char* message_text_; // Complete message text (points to selected buffer)
954 const char severity_; // What level is this LogMessage logged at?
955 int line_; // line number where logging call is.
956 void (LogMessage::*send_method_)(); // Call this in destructor to send
957 union { // At most one of these is used: union to keep the size low.
958 LogSink* sink_; // NULL or sink to send message to
959 std::vector<std::string>* outvec_; // NULL or vector to push message onto
961 time_t timestamp_; // Time of creation of LogMessage
962 struct ::tm tm_time_; // Time of creation of LogMessage
963 size_t num_prefix_chars_; // How many chars of "prefix" for this message?
964 size_t num_chars_to_log_; // How many chars of msg to send to log?
965 size_t num_chars_to_syslog_; // How many chars of msg to send to syslog?
967 const char* basename_; // basename of the file which called LOG.
968 const char* fullname_; // full name (including directory)
969 // of the file which called LOG.
971 bool has_been_flushed_; // False if data has not yet been flushed.
973 LogMessageData(int preserved_errno, LogSeverity severity, int ctr);
977 LogMessageData(const LogMessageData&);
978 void operator=(const LogMessageData&);
981 LogMessageData* allocated_;
982 LogMessageData* data_;
984 friend class LogDestination;
986 LogMessage(const LogMessage&);
987 void operator=(const LogMessage&);
990 // This class happens to be thread-hostile because all instances share
991 // a single data buffer, but since it can only be created just before
992 // the process dies, we don't worry so much.
993 class LogMessageFatal : public LogMessage {
995 LogMessageFatal(const char* file, int line);
996 LogMessageFatal(const char* file, int line, const CheckOpString& result);
997 ~LogMessageFatal() @ac_cv___attribute___noreturn@;
1000 // A non-macro interface to the log facility; (useful
1001 // when the logging level is not a compile-time constant).
1002 inline void LogAtLevel(int const log_level, std::string const &msg) {
1003 LogMessage(__FILE__, __LINE__, log_level).stream() << msg;
1006 // A small helper for CHECK_NOTNULL().
1007 template <typename T>
1008 T* CheckNotNull(const char *file, int line, const char *names, T* t) {
1010 LogMessageFatal(file, line, new std::string(names));
1015 // Allow folks to put a counter in the LOG_EVERY_X()'ed messages. This
1016 // only works if ostream is a LogStream. If the ostream is not a
1017 // LogStream you'll get an assert saying as much at runtime.
1018 std::ostream& operator<<(std::ostream &os, const PRIVATE_Counter&);
1021 // Derived class for PLOG*() above.
1022 class ErrnoLogMessage : public LogMessage {
1025 ErrnoLogMessage(const char* file, int line, LogSeverity severity, int ctr,
1026 void (LogMessage::*send_method)());
1028 // Postpends ": strerror(errno) [errno]".
1032 ErrnoLogMessage(const ErrnoLogMessage&);
1033 void operator=(const ErrnoLogMessage&);
1037 // This class is used to explicitly ignore values in the conditional
1038 // logging macros. This avoids compiler warnings like "value computed
1039 // is not used" and "statement has no effect".
1041 class LogMessageVoidify {
1043 LogMessageVoidify() { }
1044 // This has to be an operator with a precedence lower than << but
1046 void operator&(std::ostream&) { }
1050 // Flushes all log files that contains messages that are at least of
1051 // the specified severity level. Thread-safe.
1052 void FlushLogFiles(LogSeverity min_severity);
1054 // Flushes all log files that contains messages that are at least of
1055 // the specified severity level. Thread-hostile because it ignores
1056 // locking -- used for catastrophic failures.
1057 void FlushLogFilesUnsafe(LogSeverity min_severity);
1060 // Set the destination to which a particular severity level of log
1061 // messages is sent. If base_filename is "", it means "don't log this
1062 // severity". Thread-safe.
1064 void SetLogDestination(LogSeverity severity, const char* base_filename);
1067 // Set the basename of the symlink to the latest log file at a given
1068 // severity. If symlink_basename is empty, do not make a symlink. If
1069 // you don't call this function, the symlink basename is the
1070 // invocation name of the program. Thread-safe.
1072 void SetLogSymlink(LogSeverity severity, const char* symlink_basename);
1075 // Used to send logs to some other kind of destination
1076 // Users should subclass LogSink and override send to do whatever they want.
1077 // Implementations must be thread-safe because a shared instance will
1078 // be called from whichever thread ran the LOG(XXX) line.
1083 // Sink's logging logic (message_len is such as to exclude '\n' at the end).
1084 // This method can't use LOG() or CHECK() as logging system mutex(s) are held
1085 // during this call.
1086 virtual void send(LogSeverity severity, const char* full_filename,
1087 const char* base_filename, int line,
1088 const struct ::tm* tm_time,
1089 const char* message, size_t message_len) = 0;
1091 // Redefine this to implement waiting for
1092 // the sink's logging logic to complete.
1093 // It will be called after each send() returns,
1094 // but before that LogMessage exits or crashes.
1095 // By default this function does nothing.
1096 // Using this function one can implement complex logic for send()
1097 // that itself involves logging; and do all this w/o causing deadlocks and
1098 // inconsistent rearrangement of log messages.
1099 // E.g. if a LogSink has thread-specific actions, the send() method
1100 // can simply add the message to a queue and wake up another thread that
1101 // handles real logging while itself making some LOG() calls;
1102 // WaitTillSent() can be implemented to wait for that logic to complete.
1103 // See our unittest for an example.
1104 virtual void WaitTillSent();
1106 // Returns the normal text output of the log message.
1107 // Can be useful to implement send().
1108 static std::string ToString(LogSeverity severity, const char* file, int line,
1109 const struct ::tm* tm_time,
1110 const char* message, size_t message_len);
1113 // Add or remove a LogSink as a consumer of logging data. Thread-safe.
1114 void AddLogSink(LogSink *destination);
1115 void RemoveLogSink(LogSink *destination);
1118 // Specify an "extension" added to the filename specified via
1119 // SetLogDestination. This applies to all severity levels. It's
1120 // often used to append the port we're listening on to the logfile
1121 // name. Thread-safe.
1123 void SetLogFilenameExtension(const char* filename_extension);
1126 // Make it so that all log messages of at least a particular severity
1127 // are logged to stderr (in addition to logging to the usual log
1128 // file(s)). Thread-safe.
1130 void SetStderrLogging(LogSeverity min_severity);
1133 // Make it so that all log messages go only to stderr. Thread-safe.
1138 // Make it so that all log messages of at least a particular severity are
1139 // logged via email to a list of addresses (in addition to logging to the
1140 // usual log file(s)). The list of addresses is just a string containing
1141 // the email addresses to send to (separated by spaces, say). Thread-safe.
1143 void SetEmailLogging(LogSeverity min_severity, const char* addresses);
1145 // A simple function that sends email. dest is a commma-separated
1146 // list of addressess. Thread-safe.
1147 bool SendEmail(const char*dest, const char *subject, const char*body);
1149 const std::vector<std::string>& GetLoggingDirectories();
1151 // For tests only: Clear the internal [cached] list of logging directories to
1152 // force a refresh the next time GetLoggingDirectories is called.
1154 void TestOnly_ClearLoggingDirectoriesList();
1156 // Returns a set of existing temporary directories, which will be a
1157 // subset of the directories returned by GetLogginDirectories().
1159 void GetExistingTempDirectories(std::vector<std::string>* list);
1161 // Print any fatal message again -- useful to call from signal handler
1162 // so that the last thing in the output is the fatal message.
1163 // Thread-hostile, but a race is unlikely.
1164 void ReprintFatalMessage();
1166 // Truncate a log file that may be the append-only output of multiple
1167 // processes and hence can't simply be renamed/reopened (typically a
1168 // stdout/stderr). If the file "path" is > "limit" bytes, copy the
1169 // last "keep" bytes to offset 0 and truncate the rest. Since we could
1170 // be racing with other writers, this approach has the potential to
1171 // lose very small amounts of data. For security, only follow symlinks
1172 // if the path is /proc/self/fd/*
1173 void TruncateLogFile(const char *path, int64 limit, int64 keep);
1175 // Truncate stdout and stderr if they are over the value specified by
1176 // --max_log_size; keep the final 1MB. This function has the same
1177 // race condition as TruncateLogFile.
1178 void TruncateStdoutStderr();
1180 // Return the string representation of the provided LogSeverity level.
1182 const char* GetLogSeverityName(LogSeverity severity);
1184 // ---------------------------------------------------------------------
1185 // Implementation details that are not useful to most clients
1186 // ---------------------------------------------------------------------
1188 // A Logger is the interface used by logging modules to emit entries
1189 // to a log. A typical implementation will dump formatted data to a
1190 // sequence of files. We also provide interfaces that will forward
1191 // the data to another thread so that the invoker never blocks.
1192 // Implementations should be thread-safe since the logging system
1193 // will write to them from multiple threads.
1201 // Writes "message[0,message_len-1]" corresponding to an event that
1202 // occurred at "timestamp". If "force_flush" is true, the log file
1203 // is flushed immediately.
1205 // The input message has already been formatted as deemed
1206 // appropriate by the higher level logging facility. For example,
1207 // textual log messages already contain timestamps, and the
1208 // file:linenumber header.
1209 virtual void Write(bool force_flush,
1211 const char* message,
1212 int message_len) = 0;
1214 // Flush any buffered messages
1215 virtual void Flush() = 0;
1217 // Get the current LOG file size.
1218 // The returned value is approximate since some
1219 // logged data may not have been flushed to disk yet.
1220 virtual uint32 LogSize() = 0;
1223 // Get the logger for the specified severity level. The logger
1224 // remains the property of the logging module and should not be
1225 // deleted by the caller. Thread-safe.
1226 extern Logger* GetLogger(LogSeverity level);
1228 // Set the logger for the specified severity level. The logger
1229 // becomes the property of the logging module and should not
1230 // be deleted by the caller. Thread-safe.
1231 extern void SetLogger(LogSeverity level, Logger* logger);
1235 // glibc has traditionally implemented two incompatible versions of
1236 // strerror_r(). There is a poorly defined convention for picking the
1237 // version that we want, but it is not clear whether it even works with
1238 // all versions of glibc.
1239 // So, instead, we provide this wrapper that automatically detects the
1240 // version that is in use, and then implements POSIX semantics.
1241 // N.B. In addition to what POSIX says, we also guarantee that "buf" will
1242 // be set to an empty string, if this function failed. This means, in most
1243 // cases, you do not need to check the error code and you can directly
1244 // use the value of "buf". It will never have an undefined value.
1245 int posix_strerror_r(int err, char *buf, size_t len);
1248 // A class for which we define operator<<, which does nothing.
1249 class NullStream : public LogMessage::LogStream {
1251 // Initialize the LogStream so the messages can be written somewhere
1252 // (they'll never be actually displayed). This will be needed if a
1253 // NullStream& is implicitly converted to LogStream&, in which case
1254 // the overloaded NullStream::operator<< will not be invoked.
1255 NullStream() : LogMessage::LogStream(message_buffer_, 1, 0) { }
1256 NullStream &stream() { return *this; }
1258 // A very short buffer for messages (which we discard anyway). This
1259 // will be needed if NullStream& converted to LogStream& (e.g. as a
1260 // result of a conditional expression).
1261 char message_buffer_[2];
1264 // Do nothing. This operator is inline, allowing the message to be
1265 // compiled away. The message will not be compiled away if we do
1266 // something like (flag ? LOG(INFO) : LOG(ERROR)) << message; when
1267 // SKIP_LOG=WARNING. In those cases, NullStream will be implicitly
1268 // converted to LogStream and the message will be computed and then
1269 // quietly discarded.
1271 inline NullStream& operator<<(NullStream &str, const T &value) { return str; }
1273 // Similar to NullStream, but aborts the program (without stack
1274 // trace), like LogMessageFatal.
1275 class NullStreamFatal : public NullStream {
1277 @ac_cv___attribute___noreturn@ ~NullStreamFatal() { _exit(1); }
1280 // Install a signal handler that will dump signal information and a stack
1281 // trace when the program crashes on certain signals. We'll install the
1282 // signal handler for the following signals.
1284 // SIGSEGV, SIGILL, SIGFPE, SIGABRT, SIGBUS, and SIGTERM.
1286 // By default, the signal handler will write the failure dump to the
1287 // standard error. You can customize the destination by installing your
1288 // own writer function by InstallFailureWriter() below.
1290 // Note on threading:
1292 // The function should be called before threads are created, if you want
1293 // to use the failure signal handler for all threads. The stack trace
1294 // will be shown only for the thread that receives the signal. In other
1295 // words, stack traces of other threads won't be shown.
1296 void InstallFailureSignalHandler();
1298 // Installs a function that is used for writing the failure dump. "data"
1299 // is the pointer to the beginning of a message to be written, and "size"
1300 // is the size of the message. You should not expect the data is
1301 // terminated with '\0'.
1302 void InstallFailureWriter(void (*writer)(const char* data, int size));
1304 @ac_google_end_namespace@
1306 #endif // _LOGGING_H_