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 // A macro to disallow the evil copy constructor and operator= functions
98 // This should be used in the private: declarations for a class
99 #define DISALLOW_EVIL_CONSTRUCTORS(TypeName) \
100 TypeName(const TypeName&); \
101 void operator=(const TypeName&)
103 // Make a bunch of macros for logging. The way to log things is to stream
104 // things to LOG(<a particular severity level>). E.g.,
106 // LOG(INFO) << "Found " << num_cookies << " cookies";
108 // You can capture log messages in a string, rather than reporting them
111 // vector<string> errors;
112 // LOG_STRING(ERROR, &errors) << "Couldn't parse cookie #" << cookie_num;
114 // This pushes back the new error onto 'errors'; if given a NULL pointer,
115 // it reports the error via LOG(ERROR).
117 // You can also do conditional logging:
119 // LOG_IF(INFO, num_cookies > 10) << "Got lots of cookies";
121 // You can also do occasional logging (log every n'th occurrence of an
124 // LOG_EVERY_N(INFO, 10) << "Got the " << COUNTER << "th cookie";
126 // The above will cause log messages to be output on the 1st, 11th, 21st, ...
127 // times it is executed. Note that the special COUNTER value is used to
128 // identify which repetition is happening.
130 // You can also do occasional conditional logging (log every n'th
131 // occurrence of an event, when condition is satisfied):
133 // LOG_IF_EVERY_N(INFO, (size > 1024), 10) << "Got the " << COUNTER
134 // << "th big cookie";
136 // You can log messages the first N times your code executes a line. E.g.
138 // LOG_FIRST_N(INFO, 20) << "Got the " << COUNTER << "th cookie";
140 // Outputs log messages for the first 20 times it is executed.
142 // Analogous SYSLOG, SYSLOG_IF, and SYSLOG_EVERY_N macros are available.
143 // These log to syslog as well as to the normal logs. If you use these at
144 // all, you need to be aware that syslog can drastically reduce performance,
145 // especially if it is configured for remote logging! Don't use these
146 // unless you fully understand this and have a concrete need to use them.
147 // Even then, try to minimize your use of them.
149 // There are also "debug mode" logging macros like the ones above:
151 // DLOG(INFO) << "Found cookies";
153 // DLOG_IF(INFO, num_cookies > 10) << "Got lots of cookies";
155 // DLOG_EVERY_N(INFO, 10) << "Got the " << COUNTER << "th cookie";
157 // All "debug mode" logging is compiled away to nothing for non-debug mode
162 // LOG_ASSERT(assertion);
163 // DLOG_ASSERT(assertion);
165 // which is syntactic sugar for {,D}LOG_IF(FATAL, assert fails) << assertion;
167 // There are "verbose level" logging macros. They look like
169 // VLOG(1) << "I'm printed when you run the program with --v=1 or more";
170 // VLOG(2) << "I'm printed when you run the program with --v=2 or more";
172 // These always log at the INFO log level (when they log at all).
173 // The verbose logging can also be turned on module-by-module. For instance,
174 // --vmodule=mapreduce=2,file=1,gfs*=3 --v=0
176 // a. VLOG(2) and lower messages to be printed from mapreduce.{h,cc}
177 // b. VLOG(1) and lower messages to be printed from file.{h,cc}
178 // c. VLOG(3) and lower messages to be printed from files prefixed with "gfs"
179 // d. VLOG(0) and lower messages to be printed from elsewhere
181 // The wildcarding functionality shown by (c) supports both '*' (match
182 // 0 or more characters) and '?' (match any single character) wildcards.
184 // There's also VLOG_IS_ON(n) "verbose level" condition macro. To be used as
186 // if (VLOG_IS_ON(2)) {
187 // // do some logging preparation and logging
188 // // that can't be accomplished with just VLOG(2) << ...;
191 // There are also VLOG_IF, VLOG_EVERY_N and VLOG_IF_EVERY_N "verbose level"
192 // condition macros for sample cases, when some extra computation and
193 // preparation for logs is not needed.
194 // VLOG_IF(1, (size > 1024))
195 // << "I'm printed when size is more than 1024 and when you run the "
196 // "program with --v=1 or more";
197 // VLOG_EVERY_N(1, 10)
198 // << "I'm printed every 10th occurrence, and when you run the program "
199 // "with --v=1 or more. Present occurence is " << COUNTER;
200 // VLOG_IF_EVERY_N(1, (size > 1024), 10)
201 // << "I'm printed on every 10th occurence of case when size is more "
202 // " than 1024, when you run the program with --v=1 or more. ";
203 // "Present occurence is " << COUNTER;
205 // The supported severity levels for macros that allow you to specify one
206 // are (in increasing order of severity) INFO, WARNING, ERROR, and FATAL.
207 // Note that messages of a given severity are logged not only in the
208 // logfile for that severity, but also in all logfiles of lower severity.
209 // E.g., a message of severity FATAL will be logged to the logfiles of
210 // severity FATAL, ERROR, WARNING, and INFO.
212 // There is also the special severity of DFATAL, which logs FATAL in
213 // debug mode, ERROR in normal mode.
215 // Very important: logging a message at the FATAL severity level causes
216 // the program to terminate (after the message is logged).
218 // Unless otherwise specified, logs will be written to the filename
219 // "<program name>.<hostname>.<user name>.log.<severity level>.", followed
220 // by the date, time, and pid (you can't prevent the date, time, and pid
221 // from being in the filename).
223 // The logging code takes two flags:
224 // --v=# set the verbose level
225 // --logtostderr log all the messages to stderr instead of to logfiles
227 #ifndef DECLARE_VARIABLE
228 #define MUST_UNDEF_GFLAGS_DECLARE_MACROS
229 #define DECLARE_VARIABLE(type, name, tn) \
230 namespace FLAG__namespace_do_not_use_directly_use_DECLARE_##tn##_instead { \
231 extern type FLAGS_##name; \
233 using FLAG__namespace_do_not_use_directly_use_DECLARE_##tn##_instead::FLAGS_##name
235 // bool specialization
236 #define DECLARE_bool(name) \
237 DECLARE_VARIABLE(bool, name, bool)
239 // int32 specialization
240 #define DECLARE_int32(name) \
241 DECLARE_VARIABLE(@ac_google_namespace@::int32, name, int32)
243 // Special case for string, because we have to specify the namespace
244 // std::string, which doesn't play nicely with our FLAG__namespace hackery.
245 #define DECLARE_string(name) \
246 namespace FLAG__namespace_do_not_use_directly_use_DECLARE_string_instead { \
247 extern std::string FLAGS_##name; \
249 using FLAG__namespace_do_not_use_directly_use_DECLARE_string_instead::FLAGS_##name
252 // Set whether log messages go to stderr instead of logfiles
253 DECLARE_bool(logtostderr);
255 // Set how important a log message should be to avoid buffering
256 DECLARE_int32(logbuflevel);
258 // Log suppression level: messages logged at a lower level than this
260 DECLARE_int32(minloglevel);
262 // If specified, logfiles are written into this directory instead of the
263 // default logging directory.
264 DECLARE_string(log_dir);
266 DECLARE_int32(v); // in vlog_is_on.cc
268 DECLARE_int32(stderrthreshold);
269 DECLARE_bool(alsologtostderr);
271 #ifdef MUST_UNDEF_GFLAGS_DECLARE_MACROS
272 #undef MUST_UNDEF_GFLAGS_DECLARE_MACROS
273 #undef DECLARE_VARIABLE
276 #undef DECLARE_string
279 // Log messages below the GOOGLE_STRIP_LOG level will be compiled away for
280 // security reasons. See LOG(severtiy) below.
282 // A few definitions of macros that don't generate much code. Since
283 // LOG(INFO) and its ilk are used all over our code, it's
284 // better to have compact code for these operations.
286 #if 0 >= GOOGLE_STRIP_LOG
287 #define COMPACT_GOOGLE_LOG_INFO @ac_google_namespace@::LogMessage(__FILE__, __LINE__)
289 #define COMPACT_GOOGLE_LOG_INFO @ac_google_namespace@::NullStream()
292 #if 1 >= GOOGLE_STRIP_LOG
293 #define COMPACT_GOOGLE_LOG_WARNING @ac_google_namespace@::LogMessage(__FILE__, __LINE__, @ac_google_namespace@::WARNING)
295 #define COMPACT_GOOGLE_LOG_WARNING @ac_google_namespace@::NullStream()
298 #if 2 >= GOOGLE_STRIP_LOG
299 #define COMPACT_GOOGLE_LOG_ERROR @ac_google_namespace@::LogMessage(__FILE__, __LINE__, @ac_google_namespace@::ERROR)
301 #define COMPACT_GOOGLE_LOG_ERROR @ac_google_namespace@::NullStream()
304 #if 3 >= GOOGLE_STRIP_LOG
305 #define COMPACT_GOOGLE_LOG_FATAL @ac_google_namespace@::LogMessageFatal(__FILE__, __LINE__)
307 #define COMPACT_GOOGLE_LOG_FATAL @ac_google_namespace@::NullStreamFatal()
310 // For DFATAL, we want to use LogMessage (as opposed to
311 // LogMessageFatal), to be consistent with the original behavior.
313 #define COMPACT_GOOGLE_LOG_DFATAL COMPACT_GOOGLE_LOG_ERROR
314 #elif 3 >= GOOGLE_STRIP_LOG
315 #define COMPACT_GOOGLE_LOG_DFATAL @ac_google_namespace@::LogMessage(__FILE__, __LINE__, @ac_google_namespace@::FATAL)
317 #define COMPACT_GOOGLE_LOG_DFATAL @ac_google_namespace@::NullStreamFatal()
320 #define GOOGLE_LOG_INFO(counter) @ac_google_namespace@::LogMessage(__FILE__, __LINE__, @ac_google_namespace@::INFO, counter, &@ac_google_namespace@::LogMessage::SendToLog)
321 #define SYSLOG_INFO(counter) \
322 @ac_google_namespace@::LogMessage(__FILE__, __LINE__, @ac_google_namespace@::INFO, counter, \
323 &@ac_google_namespace@::LogMessage::SendToSyslogAndLog)
324 #define GOOGLE_LOG_WARNING(counter) \
325 @ac_google_namespace@::LogMessage(__FILE__, __LINE__, @ac_google_namespace@::WARNING, counter, \
326 &@ac_google_namespace@::LogMessage::SendToLog)
327 #define SYSLOG_WARNING(counter) \
328 @ac_google_namespace@::LogMessage(__FILE__, __LINE__, @ac_google_namespace@::WARNING, counter, \
329 &@ac_google_namespace@::LogMessage::SendToSyslogAndLog)
330 #define GOOGLE_LOG_ERROR(counter) \
331 @ac_google_namespace@::LogMessage(__FILE__, __LINE__, @ac_google_namespace@::ERROR, counter, \
332 &@ac_google_namespace@::LogMessage::SendToLog)
333 #define SYSLOG_ERROR(counter) \
334 @ac_google_namespace@::LogMessage(__FILE__, __LINE__, @ac_google_namespace@::ERROR, counter, \
335 &@ac_google_namespace@::LogMessage::SendToSyslogAndLog)
336 #define GOOGLE_LOG_FATAL(counter) \
337 @ac_google_namespace@::LogMessage(__FILE__, __LINE__, @ac_google_namespace@::FATAL, counter, \
338 &@ac_google_namespace@::LogMessage::SendToLog)
339 #define SYSLOG_FATAL(counter) \
340 @ac_google_namespace@::LogMessage(__FILE__, __LINE__, @ac_google_namespace@::FATAL, counter, \
341 &@ac_google_namespace@::LogMessage::SendToSyslogAndLog)
342 #define GOOGLE_LOG_DFATAL(counter) \
343 @ac_google_namespace@::LogMessage(__FILE__, __LINE__, @ac_google_namespace@::DFATAL_LEVEL, counter, \
344 &@ac_google_namespace@::LogMessage::SendToLog)
345 #define SYSLOG_DFATAL(counter) \
346 @ac_google_namespace@::LogMessage(__FILE__, __LINE__, @ac_google_namespace@::DFATAL_LEVEL, counter, \
347 &@ac_google_namespace@::LogMessage::SendToSyslogAndLog)
349 #if defined(WIN32) || defined(_WIN32) || defined(__WIN32__) || defined(__CYGWIN__) || defined(__CYGWIN32__)
350 // A very useful logging macro to log windows errors:
351 #define LOG_SYSRESULT(result) \
352 if (FAILED(result)) { \
353 LPTSTR message = NULL; \
354 LPTSTR msg = reinterpret_cast<LPTSTR>(&message); \
355 DWORD message_length = FormatMessage(FORMAT_MESSAGE_ALLOCATE_BUFFER | \
356 FORMAT_MESSAGE_FROM_SYSTEM, \
357 0, result, 0, msg, 100, NULL); \
358 if (message_length > 0) { \
359 @ac_google_namespace@::LogMessage(__FILE__, __LINE__, ERROR, 0, \
360 &@ac_google_namespace@::LogMessage::SendToLog).stream() << message; \
361 LocalFree(message); \
366 // We use the preprocessor's merging operator, "##", so that, e.g.,
367 // LOG(INFO) becomes the token GOOGLE_LOG_INFO. There's some funny
368 // subtle difference between ostream member streaming functions (e.g.,
369 // ostream::operator<<(int) and ostream non-member streaming functions
370 // (e.g., ::operator<<(ostream&, string&): it turns out that it's
371 // impossible to stream something like a string directly to an unnamed
372 // ostream. We employ a neat hack by calling the stream() member
373 // function of LogMessage which seems to avoid the problem.
374 #define LOG(severity) COMPACT_GOOGLE_LOG_ ## severity.stream()
375 #define SYSLOG(severity) SYSLOG_ ## severity(0).stream()
377 @ac_google_start_namespace@
379 // They need the definitions of integer types.
380 #include "glog/log_severity.h"
381 #include "glog/vlog_is_on.h"
383 // Initialize google's logging library. You will see the program name
384 // specified by argv0 in log outputs.
385 void InitGoogleLogging(const char* argv0);
387 // Install a function which will be called after LOG(FATAL).
388 void InstallFailureFunction(void (*fail_func)());
390 class LogSink; // defined below
392 // If a non-NULL sink pointer is given, we push this message to that sink.
393 // We then do normal LOG(severity) logging as well.
394 // This is useful for capturing messages and passing/storing them
395 // somewhere more specific than the global log of the process.
398 // LogSeverity severity;
399 // The cast is to disambiguate NULL arguments.
400 #define LOG_TO_SINK(sink, severity) \
401 @ac_google_namespace@::LogMessage(__FILE__, __LINE__, @ac_google_namespace@::severity, \
402 static_cast<@ac_google_namespace@::LogSink*>(sink)).stream()
404 // If a non-NULL pointer is given, we push the message onto the end
405 // of a vector of strings; otherwise, we report it with LOG(severity).
406 // This is handy for capturing messages and perhaps passing them back
407 // to the caller, rather than reporting them immediately.
409 // LogSeverity severity;
410 // vector<string> *outvec;
411 // The cast is to disambiguate NULL arguments.
412 #define LOG_STRING(severity, outvec) \
413 @ac_google_namespace@::LogMessage(__FILE__, __LINE__, @ac_google_namespace@::severity, \
414 static_cast<std::vector<std::string>*>(outvec)).stream()
416 #define LOG_IF(severity, condition) \
417 !(condition) ? (void) 0 : @ac_google_namespace@::LogMessageVoidify() & LOG(severity)
418 #define SYSLOG_IF(severity, condition) \
419 !(condition) ? (void) 0 : @ac_google_namespace@::LogMessageVoidify() & SYSLOG(severity)
421 #define LOG_ASSERT(condition) \
422 LOG_IF(FATAL, !(condition)) << "Assert failed: " #condition
423 #define SYSLOG_ASSERT(condition) \
424 SYSLOG_IF(FATAL, !(condition)) << "Assert failed: " #condition
426 // CHECK dies with a fatal error if condition is not true. It is *not*
427 // controlled by NDEBUG, so the check will be executed regardless of
428 // compilation mode. Therefore, it is safe to do things like:
429 // CHECK(fp->Write(x) == 4)
430 #define CHECK(condition) \
431 LOG_IF(FATAL, GOOGLE_PREDICT_BRANCH_NOT_TAKEN(!(condition))) \
432 << "Check failed: " #condition " "
434 // A container for a string pointer which can be evaluated to a bool -
435 // true iff the pointer is NULL.
436 struct CheckOpString {
437 CheckOpString(std::string* str) : str_(str) { }
438 // No destructor: if str_ is non-NULL, we're about to LOG(FATAL),
439 // so there's no point in cleaning up str_.
440 operator bool() const {
441 return GOOGLE_PREDICT_BRANCH_NOT_TAKEN(str_ != NULL);
446 // Function is overloaded for integral types to allow static const
447 // integrals declared in classes and not defined to be used as arguments to
448 // CHECK* macros. It's not encouraged though.
450 inline const T& GetReferenceableValue(const T& t) { return t; }
451 inline char GetReferenceableValue(char t) { return t; }
452 inline unsigned char GetReferenceableValue(unsigned char t) { return t; }
453 inline signed char GetReferenceableValue(signed char t) { return t; }
454 inline short GetReferenceableValue(short t) { return t; }
455 inline unsigned short GetReferenceableValue(unsigned short t) { return t; }
456 inline int GetReferenceableValue(int t) { return t; }
457 inline unsigned int GetReferenceableValue(unsigned int t) { return t; }
458 inline long GetReferenceableValue(long t) { return t; }
459 inline unsigned long GetReferenceableValue(unsigned long t) { return t; }
460 inline long long GetReferenceableValue(long long t) { return t; }
461 inline unsigned long long GetReferenceableValue(unsigned long long t) {
465 // This is a dummy class to define the following operator.
466 struct DummyClassToDefineOperator {};
468 @ac_google_end_namespace@
470 // Define global operator<< to declare using ::operator<<.
471 // This declaration will allow use to use CHECK macros for user
472 // defined classes which have operator<< (e.g., stl_logging.h).
473 inline std::ostream& operator<<(
474 std::ostream& out, const google::DummyClassToDefineOperator& dummy) {
478 @ac_google_start_namespace@
480 // Build the error message string.
481 template<class t1, class t2>
482 std::string* MakeCheckOpString(const t1& v1, const t2& v2, const char* names) {
483 // It means that we cannot use stl_logging if compiler doesn't
484 // support using expression for operator.
485 // TODO(hamaji): Figure out a way to fix.
486 #if @ac_cv_cxx_using_operator@
490 ss << names << " (" << v1 << " vs. " << v2 << ")";
491 return new std::string(ss.str(), ss.pcount());
494 // Helper functions for CHECK_OP macro.
495 // The (int, int) specialization works around the issue that the compiler
496 // will not instantiate the template version of the function on values of
497 // unnamed enum type - see comment below.
498 #define DEFINE_CHECK_OP_IMPL(name, op) \
499 template <class t1, class t2> \
500 inline std::string* Check##name##Impl(const t1& v1, const t2& v2, \
501 const char* names) { \
502 if (v1 op v2) return NULL; \
503 else return MakeCheckOpString(v1, v2, names); \
505 inline std::string* Check##name##Impl(int v1, int v2, const char* names) { \
506 return Check##name##Impl<int, int>(v1, v2, names); \
509 // Use _EQ, _NE, _LE, etc. in case the file including base/logging.h
510 // provides its own #defines for the simpler names EQ, NE, LE, etc.
511 // This happens if, for example, those are used as token names in a
513 DEFINE_CHECK_OP_IMPL(_EQ, ==)
514 DEFINE_CHECK_OP_IMPL(_NE, !=)
515 DEFINE_CHECK_OP_IMPL(_LE, <=)
516 DEFINE_CHECK_OP_IMPL(_LT, < )
517 DEFINE_CHECK_OP_IMPL(_GE, >=)
518 DEFINE_CHECK_OP_IMPL(_GT, > )
519 #undef DEFINE_CHECK_OP_IMPL
521 // Helper macro for binary operators.
522 // Don't use this macro directly in your code, use CHECK_EQ et al below.
524 #if defined(STATIC_ANALYSIS)
525 // Only for static analysis tool to know that it is equivalent to assert
526 #define CHECK_OP_LOG(name, op, val1, val2, log) CHECK((val1) op (val2))
527 #elif !defined(NDEBUG)
528 // In debug mode, avoid constructing CheckOpStrings if possible,
529 // to reduce the overhead of CHECK statments by 2x.
530 // Real DCHECK-heavy tests have seen 1.5x speedups.
532 // The meaning of "string" might be different between now and
533 // when this macro gets invoked (e.g., if someone is experimenting
534 // with other string implementations that get defined after this
535 // file is included). Save the current meaning now and use it
537 typedef std::string _Check_string;
538 #define CHECK_OP_LOG(name, op, val1, val2, log) \
539 while (@ac_google_namespace@::_Check_string* _result = \
540 @ac_google_namespace@::Check##name##Impl((val1), (val2), #val1 " " #op " " #val2)) \
541 log(__FILE__, __LINE__, @ac_google_namespace@::CheckOpString(_result)).stream()
543 // In optimized mode, use CheckOpString to hint to compiler that
544 // the while condition is unlikely.
545 #define CHECK_OP_LOG(name, op, val1, val2, log) \
546 while (@ac_google_namespace@::CheckOpString _result = \
547 @ac_google_namespace@::Check##name##Impl(GetReferenceableValue(val1), \
548 GetReferenceableValue(val2), \
549 #val1 " " #op " " #val2)) \
550 log(__FILE__, __LINE__, _result).stream()
551 #endif // STATIC_ANALYSIS, !NDEBUG
553 #define CHECK_OP(name, op, val1, val2) \
554 CHECK_OP_LOG(name, op, val1, val2, @ac_google_namespace@::LogMessageFatal)
556 // Equality/Inequality checks - compare two values, and log a FATAL message
557 // including the two values when the result is not as expected. The values
558 // must have operator<<(ostream, ...) defined.
560 // You may append to the error message like so:
561 // CHECK_NE(1, 2) << ": The world must be ending!";
563 // We are very careful to ensure that each argument is evaluated exactly
564 // once, and that anything which is legal to pass as a function argument is
565 // legal here. In particular, the arguments may be temporary expressions
566 // which will end up being destroyed at the end of the apparent statement,
568 // CHECK_EQ(string("abc")[1], 'b');
570 // WARNING: These don't compile correctly if one of the arguments is a pointer
571 // and the other is NULL. To work around this, simply static_cast NULL to the
572 // type of the desired pointer.
574 #define CHECK_EQ(val1, val2) CHECK_OP(_EQ, ==, val1, val2)
575 #define CHECK_NE(val1, val2) CHECK_OP(_NE, !=, val1, val2)
576 #define CHECK_LE(val1, val2) CHECK_OP(_LE, <=, val1, val2)
577 #define CHECK_LT(val1, val2) CHECK_OP(_LT, < , val1, val2)
578 #define CHECK_GE(val1, val2) CHECK_OP(_GE, >=, val1, val2)
579 #define CHECK_GT(val1, val2) CHECK_OP(_GT, > , val1, val2)
581 // Check that the input is non NULL. This very useful in constructor
582 // initializer lists.
584 #define CHECK_NOTNULL(val) \
585 @ac_google_namespace@::CheckNotNull(__FILE__, __LINE__, "'" #val "' Must be non NULL", (val))
587 // Helper functions for string comparisons.
588 // To avoid bloat, the definitions are in logging.cc.
589 #define DECLARE_CHECK_STROP_IMPL(func, expected) \
590 std::string* Check##func##expected##Impl(const char* s1, const char* s2, \
592 DECLARE_CHECK_STROP_IMPL(strcmp, true)
593 DECLARE_CHECK_STROP_IMPL(strcmp, false)
594 DECLARE_CHECK_STROP_IMPL(strcasecmp, true)
595 DECLARE_CHECK_STROP_IMPL(strcasecmp, false)
596 #undef DECLARE_CHECK_STROP_IMPL
598 // Helper macro for string comparisons.
599 // Don't use this macro directly in your code, use CHECK_STREQ et al below.
600 #define CHECK_STROP(func, op, expected, s1, s2) \
601 while (@ac_google_namespace@::CheckOpString _result = \
602 @ac_google_namespace@::Check##func##expected##Impl((s1), (s2), \
603 #s1 " " #op " " #s2)) \
604 LOG(FATAL) << *_result.str_
607 // String (char*) equality/inequality checks.
608 // CASE versions are case-insensitive.
610 // Note that "s1" and "s2" may be temporary strings which are destroyed
611 // by the compiler at the end of the current "full expression"
612 // (e.g. CHECK_STREQ(Foo().c_str(), Bar().c_str())).
614 #define CHECK_STREQ(s1, s2) CHECK_STROP(strcmp, ==, true, s1, s2)
615 #define CHECK_STRNE(s1, s2) CHECK_STROP(strcmp, !=, false, s1, s2)
616 #define CHECK_STRCASEEQ(s1, s2) CHECK_STROP(strcasecmp, ==, true, s1, s2)
617 #define CHECK_STRCASENE(s1, s2) CHECK_STROP(strcasecmp, !=, false, s1, s2)
619 #define CHECK_INDEX(I,A) CHECK(I < (sizeof(A)/sizeof(A[0])))
620 #define CHECK_BOUND(B,A) CHECK(B <= (sizeof(A)/sizeof(A[0])))
622 #define CHECK_DOUBLE_EQ(val1, val2) \
624 CHECK_LE((val1), (val2)+0.000000000000001L); \
625 CHECK_GE((val1), (val2)-0.000000000000001L); \
628 #define CHECK_NEAR(val1, val2, margin) \
630 CHECK_LE((val1), (val2)+(margin)); \
631 CHECK_GE((val1), (val2)-(margin)); \
634 // perror()..googly style!
636 // PLOG() and PLOG_IF() and PCHECK() behave exactly like their LOG* and
637 // CHECK equivalents with the addition that they postpend a description
638 // of the current state of errno to their output lines.
640 #define PLOG(severity) GOOGLE_PLOG(severity, 0).stream()
642 #define GOOGLE_PLOG(severity, counter) \
643 @ac_google_namespace@::ErrnoLogMessage( \
644 __FILE__, __LINE__, @ac_google_namespace@::severity, counter, \
645 &@ac_google_namespace@::LogMessage::SendToLog)
647 #define PLOG_IF(severity, condition) \
648 !(condition) ? (void) 0 : @ac_google_namespace@::LogMessageVoidify() & PLOG(severity)
650 // A CHECK() macro that postpends errno if the condition is false. E.g.
652 // if (poll(fds, nfds, timeout) == -1) { PCHECK(errno == EINTR); ... }
653 #define PCHECK(condition) \
654 PLOG_IF(FATAL, GOOGLE_PREDICT_BRANCH_NOT_TAKEN(!(condition))) \
655 << "Check failed: " #condition " "
657 // A CHECK() macro that lets you assert the success of a function that
658 // returns -1 and sets errno in case of an error. E.g.
660 // CHECK_ERR(mkdir(path, 0700));
664 // int fd = open(filename, flags); CHECK_ERR(fd) << ": open " << filename;
665 #define CHECK_ERR(invocation) \
666 PLOG_IF(FATAL, GOOGLE_PREDICT_BRANCH_NOT_TAKEN((invocation) == -1)) \
669 // Use macro expansion to create, for each use of LOG_EVERY_N(), static
670 // variables with the __LINE__ expansion as part of the variable name.
671 #define LOG_EVERY_N_VARNAME(base, line) LOG_EVERY_N_VARNAME_CONCAT(base, line)
672 #define LOG_EVERY_N_VARNAME_CONCAT(base, line) base ## line
674 #define LOG_OCCURRENCES LOG_EVERY_N_VARNAME(occurrences_, __LINE__)
675 #define LOG_OCCURRENCES_MOD_N LOG_EVERY_N_VARNAME(occurrences_mod_n_, __LINE__)
677 #define SOME_KIND_OF_LOG_EVERY_N(severity, n, what_to_do) \
678 static int LOG_OCCURRENCES = 0, LOG_OCCURRENCES_MOD_N = 0; \
680 if (++LOG_OCCURRENCES_MOD_N > n) LOG_OCCURRENCES_MOD_N -= n; \
681 if (LOG_OCCURRENCES_MOD_N == 1) \
682 @ac_google_namespace@::LogMessage( \
683 __FILE__, __LINE__, @ac_google_namespace@::severity, LOG_OCCURRENCES, \
684 &what_to_do).stream()
686 #define SOME_KIND_OF_LOG_IF_EVERY_N(severity, condition, n, what_to_do) \
687 static int LOG_OCCURRENCES = 0, LOG_OCCURRENCES_MOD_N = 0; \
690 ((LOG_OCCURRENCES_MOD_N=(LOG_OCCURRENCES_MOD_N + 1) % n) == (1 % n))) \
691 @ac_google_namespace@::LogMessage( \
692 __FILE__, __LINE__, @ac_google_namespace@::severity, LOG_OCCURRENCES, \
693 &what_to_do).stream()
695 #define SOME_KIND_OF_PLOG_EVERY_N(severity, n, what_to_do) \
696 static int LOG_OCCURRENCES = 0, LOG_OCCURRENCES_MOD_N = 0; \
698 if (++LOG_OCCURRENCES_MOD_N > n) LOG_OCCURRENCES_MOD_N -= n; \
699 if (LOG_OCCURRENCES_MOD_N == 1) \
700 @ac_google_namespace@::ErrnoLogMessage( \
701 __FILE__, __LINE__, @ac_google_namespace@::severity, LOG_OCCURRENCES, \
702 &what_to_do).stream()
704 #define SOME_KIND_OF_LOG_FIRST_N(severity, n, what_to_do) \
705 static int LOG_OCCURRENCES = 0; \
706 if (LOG_OCCURRENCES <= n) \
708 if (LOG_OCCURRENCES <= n) \
709 @ac_google_namespace@::LogMessage( \
710 __FILE__, __LINE__, @ac_google_namespace@::severity, LOG_OCCURRENCES, \
711 &what_to_do).stream()
713 #define LOG_EVERY_N(severity, n) \
714 SOME_KIND_OF_LOG_EVERY_N(severity, (n), @ac_google_namespace@::LogMessage::SendToLog)
716 #define SYSLOG_EVERY_N(severity, n) \
717 SOME_KIND_OF_LOG_EVERY_N(severity, (n), @ac_google_namespace@::LogMessage::SendToSyslogAndLog)
719 #define PLOG_EVERY_N(severity, n) \
720 SOME_KIND_OF_PLOG_EVERY_N(severity, (n), @ac_google_namespace@::LogMessage::SendToLog)
722 #define LOG_FIRST_N(severity, n) \
723 SOME_KIND_OF_LOG_FIRST_N(severity, (n), @ac_google_namespace@::LogMessage::SendToLog)
725 #define LOG_IF_EVERY_N(severity, condition, n) \
726 SOME_KIND_OF_LOG_IF_EVERY_N(severity, (condition), (n), @ac_google_namespace@::LogMessage::SendToLog)
728 // We want the special COUNTER value available for LOG_EVERY_X()'ed messages
729 enum PRIVATE_Counter {COUNTER};
732 // Plus some debug-logging macros that get compiled to nothing for production
736 #define DLOG(severity) LOG(severity)
737 #define DLOG_IF(severity, condition) LOG_IF(severity, condition)
738 #define DLOG_EVERY_N(severity, n) LOG_EVERY_N(severity, n)
739 #define DLOG_IF_EVERY_N(severity, condition, n) \
740 LOG_IF_EVERY_N(severity, condition, n)
741 #define DLOG_ASSERT(condition) LOG_ASSERT(condition)
743 // debug-only checking. not executed in NDEBUG mode.
744 #define DCHECK(condition) CHECK(condition)
745 #define DCHECK_EQ(val1, val2) CHECK_EQ(val1, val2)
746 #define DCHECK_NE(val1, val2) CHECK_NE(val1, val2)
747 #define DCHECK_LE(val1, val2) CHECK_LE(val1, val2)
748 #define DCHECK_LT(val1, val2) CHECK_LT(val1, val2)
749 #define DCHECK_GE(val1, val2) CHECK_GE(val1, val2)
750 #define DCHECK_GT(val1, val2) CHECK_GT(val1, val2)
751 #define DCHECK_STREQ(str1, str2) CHECK_STREQ(str1, str2)
752 #define DCHECK_STRCASEEQ(str1, str2) CHECK_STRCASEEQ(str1, str2)
753 #define DCHECK_STRNE(str1, str2) CHECK_STRNE(str1, str2)
754 #define DCHECK_STRCASENE(str1, str2) CHECK_STRCASENE(str1, str2)
758 #define DLOG(severity) \
759 true ? (void) 0 : @ac_google_namespace@::LogMessageVoidify() & LOG(severity)
761 #define DLOG_IF(severity, condition) \
762 (true || !(condition)) ? (void) 0 : @ac_google_namespace@::LogMessageVoidify() & LOG(severity)
764 #define DLOG_EVERY_N(severity, n) \
765 true ? (void) 0 : @ac_google_namespace@::LogMessageVoidify() & LOG(severity)
767 #define DLOG_IF_EVERY_N(severity, condition, n) \
768 (true || !(condition))? (void) 0 : @ac_google_namespace@::LogMessageVoidify() & LOG(severity)
770 #define DLOG_ASSERT(condition) \
771 true ? (void) 0 : LOG_ASSERT(condition)
773 #define DCHECK(condition) \
777 #define DCHECK_EQ(val1, val2) \
781 #define DCHECK_NE(val1, val2) \
785 #define DCHECK_LE(val1, val2) \
789 #define DCHECK_LT(val1, val2) \
793 #define DCHECK_GE(val1, val2) \
797 #define DCHECK_GT(val1, val2) \
801 #define DCHECK_STREQ(str1, str2) \
803 CHECK_STREQ(str1, str2)
805 #define DCHECK_STRCASEEQ(str1, str2) \
807 CHECK_STRCASEEQ(str1, str2)
809 #define DCHECK_STRNE(str1, str2) \
811 CHECK_STRNE(str1, str2)
813 #define DCHECK_STRCASENE(str1, str2) \
815 CHECK_STRCASENE(str1, str2)
820 // Log only in verbose mode.
822 #define VLOG(verboselevel) LOG_IF(INFO, VLOG_IS_ON(verboselevel))
824 #define VLOG_IF(verboselevel, condition) \
825 LOG_IF(INFO, (condition) && VLOG_IS_ON(verboselevel))
827 #define VLOG_EVERY_N(verboselevel, n) \
828 LOG_IF_EVERY_N(INFO, VLOG_IS_ON(verboselevel), n)
830 #define VLOG_IF_EVERY_N(verboselevel, condition, n) \
831 LOG_IF_EVERY_N(INFO, (condition) && VLOG_IS_ON(verboselevel), n)
834 // This class more or less represents a particular log message. You
835 // create an instance of LogMessage and then stream stuff to it.
836 // When you finish streaming to it, ~LogMessage is called and the
837 // full message gets streamed to the appropriate destination.
839 // You shouldn't actually use LogMessage's constructor to log things,
840 // though. You should use the LOG() macro (and variants thereof)
845 // Passing kNoLogPrefix for the line number disables the
846 // log-message prefix. Useful for using the LogMessage
847 // infrastructure as a printing utility. See also the --log_prefix
848 // flag for controlling the log-message prefix on an
849 // application-wide basis.
853 class LogStream : public std::ostrstream {
855 LogStream(char *buf, int len, int ctr)
856 : ostrstream(buf, len),
861 int ctr() const { return ctr_; }
862 void set_ctr(int ctr) { ctr_ = ctr; }
863 LogStream* self() const { return self_; }
866 int ctr_; // Counter hack (for the LOG_EVERY_X() macro)
867 LogStream *self_; // Consistency check hack
871 // icc 8 requires this typedef to avoid an internal compiler error.
872 typedef void (LogMessage::*SendMethod)();
874 LogMessage(const char* file, int line, LogSeverity severity, int ctr,
875 SendMethod send_method);
877 // Two special constructors that generate reduced amounts of code at
878 // LOG call sites for common cases.
880 // Used for LOG(INFO): Implied are:
881 // severity = INFO, ctr = 0, send_method = &LogMessage::SendToLog.
883 // Using this constructor instead of the more complex constructor above
884 // saves 19 bytes per call site.
885 LogMessage(const char* file, int line);
887 // Used for LOG(severity) where severity != INFO. Implied
888 // are: ctr = 0, send_method = &LogMessage::SendToLog
890 // Using this constructor instead of the more complex constructor above
891 // saves 17 bytes per call site.
892 LogMessage(const char* file, int line, LogSeverity severity);
894 // Constructor to also log this message to a specified sink (if not NULL).
895 // Implied are: ctr = 0, send_method = &LogMessage::SendToSinkAndLog.
896 LogMessage(const char* file, int line, LogSeverity severity, LogSink* sink);
898 // Constructor where we also give a vector<string> pointer
899 // for storing the messages (if the pointer is not NULL).
900 // Implied are: ctr = 0, send_method = &LogMessage::SaveOrSendToLog.
901 LogMessage(const char* file, int line, LogSeverity severity,
902 std::vector<std::string>* outvec);
904 // A special constructor used for check failures
905 LogMessage(const char* file, int line, const CheckOpString& result);
909 // Flush a buffered message to the sink set in the constructor. Always
910 // called by the destructor, it may also be called from elsewhere if
911 // needed. Only the first call is actioned; any later ones are ignored.
914 // An arbitrary limit on the length of a single log message. This
915 // is so that streaming can be done more efficiently.
916 static const size_t kMaxLogMessageLen;
918 // Theses should not be called directly outside of logging.*,
919 // only passed as SendMethod arguments to other LogMessage methods:
920 void SendToLog(); // Actually dispatch to the logs
921 void SendToSyslogAndLog(); // Actually dispatch to syslog and the logs
923 // Call abort() or similar to perform LOG(FATAL) crash.
924 static void Fail() @ac_cv___attribute___noreturn@;
926 std::ostream& stream() { return data_->stream_; }
928 int preserved_errno() const { return data_->preserved_errno_; }
930 // Must be called without the log_mutex held. (L < log_mutex)
931 static int64 num_messages(int severity);
935 // Fully internal SendMethod cases:
936 void SendToSinkAndLog(); // Send to sink if provided and dispatch to the logs
937 void SaveOrSendToLog(); // Save to stringvec if provided, else to logs
939 struct LogMessageData;
941 void Init(const char* file, int line, LogSeverity severity,
942 void (LogMessage::*send_method)());
944 LogMessageData* GetMessageData(int preserved_errno, LogSeverity, int ctr);
946 // Counts of messages sent at each priority:
947 static int64 num_messages_[NUM_SEVERITIES]; // under log_mutex
949 static LogMessageData fatal_message_data_;
951 // We keep the data in a separate struct so that each instance of
952 // LogMessage uses less stack space.
953 struct LogMessageData {
954 // ORDER DEPENDENCY: preserved_errno_ comes before buf_ comes before
955 // message_text_ comes before stream_
956 int preserved_errno_; // preserved errno
958 char* message_text_; // Complete message text (points to selected buffer)
960 const char severity_; // What level is this LogMessage logged at?
961 int line_; // line number where logging call is.
962 void (LogMessage::*send_method_)(); // Call this in destructor to send
963 union { // At most one of these is used: union to keep the size low.
964 LogSink* sink_; // NULL or sink to send message to
965 std::vector<std::string>* outvec_; // NULL or vector to push message onto
967 time_t timestamp_; // Time of creation of LogMessage
968 struct ::tm tm_time_; // Time of creation of LogMessage
969 size_t num_prefix_chars_; // How many chars of "prefix" for this message?
970 size_t num_chars_to_log_; // How many chars of msg to send to log?
971 size_t num_chars_to_syslog_; // How many chars of msg to send to syslog?
973 const char* basename_; // basename of the file which called LOG.
974 const char* fullname_; // full name (including directory)
975 // of the file which called LOG.
977 bool has_been_flushed_; // False if data has not yet been flushed.
979 LogMessageData(int preserved_errno, LogSeverity severity, int ctr);
983 DISALLOW_EVIL_CONSTRUCTORS(LogMessageData);
986 LogMessageData* allocated_;
987 LogMessageData* data_;
989 friend class LogDestination;
991 DISALLOW_EVIL_CONSTRUCTORS(LogMessage);
994 // This class happens to be thread-hostile because all instances share
995 // a single data buffer, but since it can only be created just before
996 // the process dies, we don't worry so much.
997 class LogMessageFatal : public LogMessage {
999 LogMessageFatal(const char* file, int line);
1000 LogMessageFatal(const char* file, int line, const CheckOpString& result);
1001 ~LogMessageFatal() @ac_cv___attribute___noreturn@;
1004 // A non-macro interface to the log facility; (useful
1005 // when the logging level is not a compile-time constant).
1006 inline void LogAtLevel(int const log_level, std::string const &msg) {
1007 LogMessage(__FILE__, __LINE__, log_level).stream() << msg;
1010 // A small helper for CHECK_NOTNULL().
1011 template <typename T>
1012 T* CheckNotNull(const char *file, int line, const char *names, T* t) {
1014 LogMessageFatal(file, line, new std::string(names));
1019 // Allow folks to put a counter in the LOG_EVERY_X()'ed messages. This
1020 // only works if ostream is a LogStream. If the ostream is not a
1021 // LogStream you'll get an assert saying as much at runtime.
1022 std::ostream& operator<<(std::ostream &os, const PRIVATE_Counter&);
1025 // Derived class for PLOG*() above.
1026 class ErrnoLogMessage : public LogMessage {
1029 ErrnoLogMessage(const char* file, int line, LogSeverity severity, int ctr,
1030 void (LogMessage::*send_method)());
1032 // Postpends ": strerror(errno) [errno]".
1037 DISALLOW_EVIL_CONSTRUCTORS(ErrnoLogMessage);
1041 // This class is used to explicitly ignore values in the conditional
1042 // logging macros. This avoids compiler warnings like "value computed
1043 // is not used" and "statement has no effect".
1045 class LogMessageVoidify {
1047 LogMessageVoidify() { }
1048 // This has to be an operator with a precedence lower than << but
1050 void operator&(std::ostream&) { }
1054 // Flushes all log files that contains messages that are at least of
1055 // the specified severity level. Thread-safe.
1056 void FlushLogFiles(LogSeverity min_severity);
1058 // Flushes all log files that contains messages that are at least of
1059 // the specified severity level. Thread-hostile because it ignores
1060 // locking -- used for catastrophic failures.
1061 void FlushLogFilesUnsafe(LogSeverity min_severity);
1064 // Set the destination to which a particular severity level of log
1065 // messages is sent. If base_filename is "", it means "don't log this
1066 // severity". Thread-safe.
1068 void SetLogDestination(LogSeverity severity, const char* base_filename);
1071 // Set the basename of the symlink to the latest log file at a given
1072 // severity. If symlink_basename is empty, do not make a symlink. If
1073 // you don't call this function, the symlink basename is the
1074 // invocation name of the program. Thread-safe.
1076 void SetLogSymlink(LogSeverity severity, const char* symlink_basename);
1079 // Used to send logs to some other kind of destination
1080 // Users should subclass LogSink and override send to do whatever they want.
1081 // Implementations must be thread-safe because a shared instance will
1082 // be called from whichever thread ran the LOG(XXX) line.
1087 // Sink's logging logic (message_len is such as to exclude '\n' at the end).
1088 // This method can't use LOG() or CHECK() as logging system mutex(s) are held
1089 // during this call.
1090 virtual void send(LogSeverity severity, const char* full_filename,
1091 const char* base_filename, int line,
1092 const struct ::tm* tm_time,
1093 const char* message, size_t message_len) = 0;
1095 // Redefine this to implement waiting for
1096 // the sink's logging logic to complete.
1097 // It will be called after each send() returns,
1098 // but before that LogMessage exits or crashes.
1099 // By default this function does nothing.
1100 // Using this function one can implement complex logic for send()
1101 // that itself involves logging; and do all this w/o causing deadlocks and
1102 // inconsistent rearrangement of log messages.
1103 // E.g. if a LogSink has thread-specific actions, the send() method
1104 // can simply add the message to a queue and wake up another thread that
1105 // handles real logging while itself making some LOG() calls;
1106 // WaitTillSent() can be implemented to wait for that logic to complete.
1107 // See our unittest for an example.
1108 virtual void WaitTillSent();
1110 // Returns the normal text output of the log message.
1111 // Can be useful to implement send().
1112 static std::string ToString(LogSeverity severity, const char* file, int line,
1113 const struct ::tm* tm_time,
1114 const char* message, size_t message_len);
1117 // Add or remove a LogSink as a consumer of logging data. Thread-safe.
1118 void AddLogSink(LogSink *destination);
1119 void RemoveLogSink(LogSink *destination);
1122 // Specify an "extension" added to the filename specified via
1123 // SetLogDestination. This applies to all severity levels. It's
1124 // often used to append the port we're listening on to the logfile
1125 // name. Thread-safe.
1127 void SetLogFilenameExtension(const char* filename_extension);
1130 // Make it so that all log messages of at least a particular severity
1131 // are logged to stderr (in addition to logging to the usual log
1132 // file(s)). Thread-safe.
1134 void SetStderrLogging(LogSeverity min_severity);
1137 // Make it so that all log messages go only to stderr. Thread-safe.
1142 // Make it so that all log messages of at least a particular severity are
1143 // logged via email to a list of addresses (in addition to logging to the
1144 // usual log file(s)). The list of addresses is just a string containing
1145 // the email addresses to send to (separated by spaces, say). Thread-safe.
1147 void SetEmailLogging(LogSeverity min_severity, const char* addresses);
1149 // A simple function that sends email. dest is a commma-separated
1150 // list of addressess. Thread-safe.
1151 bool SendEmail(const char*dest, const char *subject, const char*body);
1153 const std::vector<std::string>& GetLoggingDirectories();
1155 // For tests only: Clear the internal [cached] list of logging directories to
1156 // force a refresh the next time GetLoggingDirectories is called.
1158 void TestOnly_ClearLoggingDirectoriesList();
1160 // Returns a set of existing temporary directories, which will be a
1161 // subset of the directories returned by GetLogginDirectories().
1163 void GetExistingTempDirectories(std::vector<std::string>* list);
1165 // Print any fatal message again -- useful to call from signal handler
1166 // so that the last thing in the output is the fatal message.
1167 // Thread-hostile, but a race is unlikely.
1168 void ReprintFatalMessage();
1170 // Truncate a log file that may be the append-only output of multiple
1171 // processes and hence can't simply be renamed/reopened (typically a
1172 // stdout/stderr). If the file "path" is > "limit" bytes, copy the
1173 // last "keep" bytes to offset 0 and truncate the rest. Since we could
1174 // be racing with other writers, this approach has the potential to
1175 // lose very small amounts of data. For security, only follow symlinks
1176 // if the path is /proc/self/fd/*
1177 void TruncateLogFile(const char *path, int64 limit, int64 keep);
1179 // Truncate stdout and stderr if they are over the value specified by
1180 // --max_log_size; keep the final 1MB. This function has the same
1181 // race condition as TruncateLogFile.
1182 void TruncateStdoutStderr();
1184 // Return the string representation of the provided LogSeverity level.
1186 const char* GetLogSeverityName(LogSeverity severity);
1188 // ---------------------------------------------------------------------
1189 // Implementation details that are not useful to most clients
1190 // ---------------------------------------------------------------------
1192 // A Logger is the interface used by logging modules to emit entries
1193 // to a log. A typical implementation will dump formatted data to a
1194 // sequence of files. We also provide interfaces that will forward
1195 // the data to another thread so that the invoker never blocks.
1196 // Implementations should be thread-safe since the logging system
1197 // will write to them from multiple threads.
1205 // Writes "message[0,message_len-1]" corresponding to an event that
1206 // occurred at "timestamp". If "force_flush" is true, the log file
1207 // is flushed immediately.
1209 // The input message has already been formatted as deemed
1210 // appropriate by the higher level logging facility. For example,
1211 // textual log messages already contain timestamps, and the
1212 // file:linenumber header.
1213 virtual void Write(bool force_flush,
1215 const char* message,
1216 int message_len) = 0;
1218 // Flush any buffered messages
1219 virtual void Flush() = 0;
1221 // Get the current LOG file size.
1222 // The returned value is approximate since some
1223 // logged data may not have been flushed to disk yet.
1224 virtual uint32 LogSize() = 0;
1227 // Get the logger for the specified severity level. The logger
1228 // remains the property of the logging module and should not be
1229 // deleted by the caller. Thread-safe.
1230 extern Logger* GetLogger(LogSeverity level);
1232 // Set the logger for the specified severity level. The logger
1233 // becomes the property of the logging module and should not
1234 // be deleted by the caller. Thread-safe.
1235 extern void SetLogger(LogSeverity level, Logger* logger);
1239 // glibc has traditionally implemented two incompatible versions of
1240 // strerror_r(). There is a poorly defined convention for picking the
1241 // version that we want, but it is not clear whether it even works with
1242 // all versions of glibc.
1243 // So, instead, we provide this wrapper that automatically detects the
1244 // version that is in use, and then implements POSIX semantics.
1245 // N.B. In addition to what POSIX says, we also guarantee that "buf" will
1246 // be set to an empty string, if this function failed. This means, in most
1247 // cases, you do not need to check the error code and you can directly
1248 // use the value of "buf". It will never have an undefined value.
1249 int posix_strerror_r(int err, char *buf, size_t len);
1252 // A class for which we define operator<<, which does nothing.
1253 class NullStream : public LogMessage::LogStream {
1255 // Initialize the LogStream so the messages can be written somewhere
1256 // (they'll never be actually displayed). This will be needed if a
1257 // NullStream& is implicitly converted to LogStream&, in which case
1258 // the overloaded NullStream::operator<< will not be invoked.
1259 NullStream() : LogMessage::LogStream(message_buffer_, 1, 0) { }
1260 NullStream &stream() { return *this; }
1262 // A very short buffer for messages (which we discard anyway). This
1263 // will be needed if NullStream& converted to LogStream& (e.g. as a
1264 // result of a conditional expression).
1265 char message_buffer_[2];
1268 // Do nothing. This operator is inline, allowing the message to be
1269 // compiled away. The message will not be compiled away if we do
1270 // something like (flag ? LOG(INFO) : LOG(ERROR)) << message; when
1271 // SKIP_LOG=WARNING. In those cases, NullStream will be implicitly
1272 // converted to LogStream and the message will be computed and then
1273 // quietly discarded.
1275 inline NullStream& operator<<(NullStream &str, const T &value) { return str; }
1277 // Similar to NullStream, but aborts the program (without stack
1278 // trace), like LogMessageFatal.
1279 class NullStreamFatal : public NullStream {
1281 @ac_cv___attribute___noreturn@ ~NullStreamFatal() { _exit(1); }
1284 // Undefine these macros not to taint namespace.
1285 #undef DISALLOW_EVIL_CONSTRUCTORS
1287 @ac_google_end_namespace@
1289 #endif // _LOGGING_H_