1 // Copyright (c) 1999, Google Inc.
2 // All rights reserved.
4 // Redistribution and use in source and binary forms, with or without
5 // modification, are permitted provided that the following conditions are
8 // * Redistributions of source code must retain the above copyright
9 // notice, this list of conditions and the following disclaimer.
10 // * Redistributions in binary form must reproduce the above
11 // copyright notice, this list of conditions and the following disclaimer
12 // in the documentation and/or other materials provided with the
14 // * Neither the name of Google Inc. nor the names of its
15 // contributors may be used to endorse or promote products derived from
16 // this software without specific prior written permission.
18 // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
19 // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
20 // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
21 // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
22 // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
23 // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
24 // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
25 // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
26 // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
27 // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
28 // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
32 // This file contains #include information about logging-related stuff.
33 // Pretty much everybody needs to #include this file so that they can
34 // log various happenings.
43 #if @ac_cv_have_unistd_h@
56 // Annoying stuff for windows -- makes sure clients can import these functions
57 #ifndef GOOGLE_GLOG_DLL_DECL
58 # if defined(_WIN32) && !defined(__CYGWIN__)
59 # define GOOGLE_GLOG_DLL_DECL __declspec(dllimport)
61 # define GOOGLE_GLOG_DLL_DECL
65 #define GLOG_MSVC_PUSH_DISABLE_WARNING(n) __pragma(warning(push)) \
66 __pragma(warning(disable:n))
67 #define GLOG_MSVC_POP_WARNING() __pragma(warning(pop))
69 #define GLOG_MSVC_PUSH_DISABLE_WARNING(n)
70 #define GLOG_MSVC_POP_WARNING()
73 // We care a lot about number of bits things take up. Unfortunately,
74 // systems define their bit-specific ints in a lot of different ways.
75 // We use our own way, and have a typedef to get there.
76 // Note: these commands below may look like "#if 1" or "#if 0", but
77 // that's because they were constructed that way at ./configure time.
78 // Look at logging.h.in to see how they're calculated (based on your config).
79 #if @ac_cv_have_stdint_h@
80 #include <stdint.h> // the normal place uint16_t is defined
82 #if @ac_cv_have_systypes_h@
83 #include <sys/types.h> // the normal place u_int16_t is defined
85 #if @ac_cv_have_inttypes_h@
86 #include <inttypes.h> // a third place for uint16_t or u_int16_t
89 #if @ac_cv_have_libgflags@
90 #include <gflags/gflags.h>
93 @ac_google_start_namespace@
95 #if @ac_cv_have_uint16_t@ // the C99 format
96 typedef int32_t int32;
97 typedef uint32_t uint32;
98 typedef int64_t int64;
99 typedef uint64_t uint64;
100 #elif @ac_cv_have_u_int16_t@ // the BSD format
101 typedef int32_t int32;
102 typedef u_int32_t uint32;
103 typedef int64_t int64;
104 typedef u_int64_t uint64;
105 #elif @ac_cv_have___uint16@ // the windows (vc7) format
106 typedef __int32 int32;
107 typedef unsigned __int32 uint32;
108 typedef __int64 int64;
109 typedef unsigned __int64 uint64;
111 #error Do not know how to define a 32-bit integer quantity on your system
114 @ac_google_end_namespace@
116 // The global value of GOOGLE_STRIP_LOG. All the messages logged to
117 // LOG(XXX) with severity less than GOOGLE_STRIP_LOG will not be displayed.
118 // If it can be determined at compile time that the message will not be
119 // printed, the statement will be compiled out.
121 // Example: to strip out all INFO and WARNING messages, use the value
122 // of 2 below. To make an exception for WARNING messages from a single
123 // file, add "#define GOOGLE_STRIP_LOG 1" to that file _before_ including
125 #ifndef GOOGLE_STRIP_LOG
126 #define GOOGLE_STRIP_LOG 0
129 // GCC can be told that a certain branch is not likely to be taken (for
130 // instance, a CHECK failure), and use that information in static analysis.
131 // Giving it this information can help it optimize for the common case in
132 // the absence of better information (ie. -fprofile-arcs).
134 #ifndef GOOGLE_PREDICT_BRANCH_NOT_TAKEN
135 #if @ac_cv_have___builtin_expect@
136 #define GOOGLE_PREDICT_BRANCH_NOT_TAKEN(x) (__builtin_expect(x, 0))
138 #define GOOGLE_PREDICT_BRANCH_NOT_TAKEN(x) x
142 // Make a bunch of macros for logging. The way to log things is to stream
143 // things to LOG(<a particular severity level>). E.g.,
145 // LOG(INFO) << "Found " << num_cookies << " cookies";
147 // You can capture log messages in a string, rather than reporting them
150 // vector<string> errors;
151 // LOG_STRING(ERROR, &errors) << "Couldn't parse cookie #" << cookie_num;
153 // This pushes back the new error onto 'errors'; if given a NULL pointer,
154 // it reports the error via LOG(ERROR).
156 // You can also do conditional logging:
158 // LOG_IF(INFO, num_cookies > 10) << "Got lots of cookies";
160 // You can also do occasional logging (log every n'th occurrence of an
163 // LOG_EVERY_N(INFO, 10) << "Got the " << google::COUNTER << "th cookie";
165 // The above will cause log messages to be output on the 1st, 11th, 21st, ...
166 // times it is executed. Note that the special google::COUNTER value is used
167 // to identify which repetition is happening.
169 // You can also do occasional conditional logging (log every n'th
170 // occurrence of an event, when condition is satisfied):
172 // LOG_IF_EVERY_N(INFO, (size > 1024), 10) << "Got the " << google::COUNTER
173 // << "th big cookie";
175 // You can log messages the first N times your code executes a line. E.g.
177 // LOG_FIRST_N(INFO, 20) << "Got the " << google::COUNTER << "th cookie";
179 // Outputs log messages for the first 20 times it is executed.
181 // Analogous SYSLOG, SYSLOG_IF, and SYSLOG_EVERY_N macros are available.
182 // These log to syslog as well as to the normal logs. If you use these at
183 // all, you need to be aware that syslog can drastically reduce performance,
184 // especially if it is configured for remote logging! Don't use these
185 // unless you fully understand this and have a concrete need to use them.
186 // Even then, try to minimize your use of them.
188 // There are also "debug mode" logging macros like the ones above:
190 // DLOG(INFO) << "Found cookies";
192 // DLOG_IF(INFO, num_cookies > 10) << "Got lots of cookies";
194 // DLOG_EVERY_N(INFO, 10) << "Got the " << google::COUNTER << "th cookie";
196 // All "debug mode" logging is compiled away to nothing for non-debug mode
201 // LOG_ASSERT(assertion);
202 // DLOG_ASSERT(assertion);
204 // which is syntactic sugar for {,D}LOG_IF(FATAL, assert fails) << assertion;
206 // There are "verbose level" logging macros. They look like
208 // VLOG(1) << "I'm printed when you run the program with --v=1 or more";
209 // VLOG(2) << "I'm printed when you run the program with --v=2 or more";
211 // These always log at the INFO log level (when they log at all).
212 // The verbose logging can also be turned on module-by-module. For instance,
213 // --vmodule=mapreduce=2,file=1,gfs*=3 --v=0
215 // a. VLOG(2) and lower messages to be printed from mapreduce.{h,cc}
216 // b. VLOG(1) and lower messages to be printed from file.{h,cc}
217 // c. VLOG(3) and lower messages to be printed from files prefixed with "gfs"
218 // d. VLOG(0) and lower messages to be printed from elsewhere
220 // The wildcarding functionality shown by (c) supports both '*' (match
221 // 0 or more characters) and '?' (match any single character) wildcards.
223 // There's also VLOG_IS_ON(n) "verbose level" condition macro. To be used as
225 // if (VLOG_IS_ON(2)) {
226 // // do some logging preparation and logging
227 // // that can't be accomplished with just VLOG(2) << ...;
230 // There are also VLOG_IF, VLOG_EVERY_N and VLOG_IF_EVERY_N "verbose level"
231 // condition macros for sample cases, when some extra computation and
232 // preparation for logs is not needed.
233 // VLOG_IF(1, (size > 1024))
234 // << "I'm printed when size is more than 1024 and when you run the "
235 // "program with --v=1 or more";
236 // VLOG_EVERY_N(1, 10)
237 // << "I'm printed every 10th occurrence, and when you run the program "
238 // "with --v=1 or more. Present occurence is " << google::COUNTER;
239 // VLOG_IF_EVERY_N(1, (size > 1024), 10)
240 // << "I'm printed on every 10th occurence of case when size is more "
241 // " than 1024, when you run the program with --v=1 or more. ";
242 // "Present occurence is " << google::COUNTER;
244 // The supported severity levels for macros that allow you to specify one
245 // are (in increasing order of severity) INFO, WARNING, ERROR, and FATAL.
246 // Note that messages of a given severity are logged not only in the
247 // logfile for that severity, but also in all logfiles of lower severity.
248 // E.g., a message of severity FATAL will be logged to the logfiles of
249 // severity FATAL, ERROR, WARNING, and INFO.
251 // There is also the special severity of DFATAL, which logs FATAL in
252 // debug mode, ERROR in normal mode.
254 // Very important: logging a message at the FATAL severity level causes
255 // the program to terminate (after the message is logged).
257 // Unless otherwise specified, logs will be written to the filename
258 // "<program name>.<hostname>.<user name>.log.<severity level>.", followed
259 // by the date, time, and pid (you can't prevent the date, time, and pid
260 // from being in the filename).
262 // The logging code takes two flags:
263 // --v=# set the verbose level
264 // --logtostderr log all the messages to stderr instead of to logfiles
266 // LOG LINE PREFIX FORMAT
268 // Log lines have this form:
270 // Lmmdd hh:mm:ss.uuuuuu threadid file:line] msg...
272 // where the fields are defined as follows:
274 // L A single character, representing the log level
276 // mm The month (zero padded; ie May is '05')
277 // dd The day (zero padded)
278 // hh:mm:ss.uuuuuu Time in hours, minutes and fractional seconds
279 // threadid The space-padded thread ID as returned by GetTID()
280 // (this matches the PID on Linux)
281 // file The file name
282 // line The line number
283 // msg The user-supplied message
287 // I1103 11:57:31.739339 24395 google.cc:2341] Command line: ./some_prog
288 // I1103 11:57:31.739403 24395 google.cc:2342] Process id 24395
290 // NOTE: although the microseconds are useful for comparing events on
291 // a single machine, clocks on different machines may not be well
292 // synchronized. Hence, use caution when comparing the low bits of
293 // timestamps from different machines.
295 #ifndef DECLARE_VARIABLE
296 #define MUST_UNDEF_GFLAGS_DECLARE_MACROS
297 #define DECLARE_VARIABLE(type, name, tn) \
298 namespace FLAG__namespace_do_not_use_directly_use_DECLARE_##tn##_instead { \
299 extern GOOGLE_GLOG_DLL_DECL type FLAGS_##name; \
301 using FLAG__namespace_do_not_use_directly_use_DECLARE_##tn##_instead::FLAGS_##name
303 // bool specialization
304 #define DECLARE_bool(name) \
305 DECLARE_VARIABLE(bool, name, bool)
307 // int32 specialization
308 #define DECLARE_int32(name) \
309 DECLARE_VARIABLE(@ac_google_namespace@::int32, name, int32)
311 // Special case for string, because we have to specify the namespace
312 // std::string, which doesn't play nicely with our FLAG__namespace hackery.
313 #define DECLARE_string(name) \
314 namespace FLAG__namespace_do_not_use_directly_use_DECLARE_string_instead { \
315 extern GOOGLE_GLOG_DLL_DECL std::string FLAGS_##name; \
317 using FLAG__namespace_do_not_use_directly_use_DECLARE_string_instead::FLAGS_##name
320 // Set whether log messages go to stderr instead of logfiles
321 DECLARE_bool(logtostderr);
323 // Set whether log messages go to stderr in addition to logfiles.
324 DECLARE_bool(alsologtostderr);
326 // Log messages at a level >= this flag are automatically sent to
327 // stderr in addition to log files.
328 DECLARE_int32(stderrthreshold);
330 // Set whether the log prefix should be prepended to each line of output.
331 DECLARE_bool(log_prefix);
333 // Log messages at a level <= this flag are buffered.
334 // Log messages at a higher level are flushed immediately.
335 DECLARE_int32(logbuflevel);
337 // Sets the maximum number of seconds which logs may be buffered for.
338 DECLARE_int32(logbufsecs);
340 // Log suppression level: messages logged at a lower level than this
342 DECLARE_int32(minloglevel);
344 // If specified, logfiles are written into this directory instead of the
345 // default logging directory.
346 DECLARE_string(log_dir);
348 // Sets the path of the directory into which to put additional links
350 DECLARE_string(log_link);
352 DECLARE_int32(v); // in vlog_is_on.cc
354 // Sets the maximum log file size (in MB).
355 DECLARE_int32(max_log_size);
357 // Sets whether to avoid logging to the disk if the disk is full.
358 DECLARE_bool(stop_logging_if_full_disk);
360 #ifdef MUST_UNDEF_GFLAGS_DECLARE_MACROS
361 #undef MUST_UNDEF_GFLAGS_DECLARE_MACROS
362 #undef DECLARE_VARIABLE
365 #undef DECLARE_string
368 // Log messages below the GOOGLE_STRIP_LOG level will be compiled away for
369 // security reasons. See LOG(severtiy) below.
371 // A few definitions of macros that don't generate much code. Since
372 // LOG(INFO) and its ilk are used all over our code, it's
373 // better to have compact code for these operations.
375 #if GOOGLE_STRIP_LOG == 0
376 #define COMPACT_GOOGLE_LOG_INFO @ac_google_namespace@::LogMessage( \
378 #define LOG_TO_STRING_INFO(message) @ac_google_namespace@::LogMessage( \
379 __FILE__, __LINE__, @ac_google_namespace@::GLOG_INFO, message)
381 #define COMPACT_GOOGLE_LOG_INFO @ac_google_namespace@::NullStream()
382 #define LOG_TO_STRING_INFO(message) @ac_google_namespace@::NullStream()
385 #if GOOGLE_STRIP_LOG <= 1
386 #define COMPACT_GOOGLE_LOG_WARNING @ac_google_namespace@::LogMessage( \
387 __FILE__, __LINE__, @ac_google_namespace@::GLOG_WARNING)
388 #define LOG_TO_STRING_WARNING(message) @ac_google_namespace@::LogMessage( \
389 __FILE__, __LINE__, @ac_google_namespace@::GLOG_WARNING, message)
391 #define COMPACT_GOOGLE_LOG_WARNING @ac_google_namespace@::NullStream()
392 #define LOG_TO_STRING_WARNING(message) @ac_google_namespace@::NullStream()
395 #if GOOGLE_STRIP_LOG <= 2
396 #define COMPACT_GOOGLE_LOG_ERROR @ac_google_namespace@::LogMessage( \
397 __FILE__, __LINE__, @ac_google_namespace@::GLOG_ERROR)
398 #define LOG_TO_STRING_ERROR(message) @ac_google_namespace@::LogMessage( \
399 __FILE__, __LINE__, @ac_google_namespace@::GLOG_ERROR, message)
401 #define COMPACT_GOOGLE_LOG_ERROR @ac_google_namespace@::NullStream()
402 #define LOG_TO_STRING_ERROR(message) @ac_google_namespace@::NullStream()
405 #if GOOGLE_STRIP_LOG <= 3
406 #define COMPACT_GOOGLE_LOG_FATAL @ac_google_namespace@::LogMessageFatal( \
408 #define LOG_TO_STRING_FATAL(message) @ac_google_namespace@::LogMessage( \
409 __FILE__, __LINE__, @ac_google_namespace@::GLOG_FATAL, message)
411 #define COMPACT_GOOGLE_LOG_FATAL @ac_google_namespace@::NullStreamFatal()
412 #define LOG_TO_STRING_FATAL(message) @ac_google_namespace@::NullStreamFatal()
415 // For DFATAL, we want to use LogMessage (as opposed to
416 // LogMessageFatal), to be consistent with the original behavior.
418 #define COMPACT_GOOGLE_LOG_DFATAL COMPACT_GOOGLE_LOG_ERROR
419 #elif GOOGLE_STRIP_LOG <= 3
420 #define COMPACT_GOOGLE_LOG_DFATAL @ac_google_namespace@::LogMessage( \
421 __FILE__, __LINE__, @ac_google_namespace@::GLOG_FATAL)
423 #define COMPACT_GOOGLE_LOG_DFATAL @ac_google_namespace@::NullStreamFatal()
426 #define GOOGLE_LOG_INFO(counter) @ac_google_namespace@::LogMessage(__FILE__, __LINE__, @ac_google_namespace@::GLOG_INFO, counter, &@ac_google_namespace@::LogMessage::SendToLog)
427 #define SYSLOG_INFO(counter) \
428 @ac_google_namespace@::LogMessage(__FILE__, __LINE__, @ac_google_namespace@::GLOG_INFO, counter, \
429 &@ac_google_namespace@::LogMessage::SendToSyslogAndLog)
430 #define GOOGLE_LOG_WARNING(counter) \
431 @ac_google_namespace@::LogMessage(__FILE__, __LINE__, @ac_google_namespace@::GLOG_WARNING, counter, \
432 &@ac_google_namespace@::LogMessage::SendToLog)
433 #define SYSLOG_WARNING(counter) \
434 @ac_google_namespace@::LogMessage(__FILE__, __LINE__, @ac_google_namespace@::GLOG_WARNING, counter, \
435 &@ac_google_namespace@::LogMessage::SendToSyslogAndLog)
436 #define GOOGLE_LOG_ERROR(counter) \
437 @ac_google_namespace@::LogMessage(__FILE__, __LINE__, @ac_google_namespace@::GLOG_ERROR, counter, \
438 &@ac_google_namespace@::LogMessage::SendToLog)
439 #define SYSLOG_ERROR(counter) \
440 @ac_google_namespace@::LogMessage(__FILE__, __LINE__, @ac_google_namespace@::GLOG_ERROR, counter, \
441 &@ac_google_namespace@::LogMessage::SendToSyslogAndLog)
442 #define GOOGLE_LOG_FATAL(counter) \
443 @ac_google_namespace@::LogMessage(__FILE__, __LINE__, @ac_google_namespace@::GLOG_FATAL, counter, \
444 &@ac_google_namespace@::LogMessage::SendToLog)
445 #define SYSLOG_FATAL(counter) \
446 @ac_google_namespace@::LogMessage(__FILE__, __LINE__, @ac_google_namespace@::GLOG_FATAL, counter, \
447 &@ac_google_namespace@::LogMessage::SendToSyslogAndLog)
448 #define GOOGLE_LOG_DFATAL(counter) \
449 @ac_google_namespace@::LogMessage(__FILE__, __LINE__, @ac_google_namespace@::DFATAL_LEVEL, counter, \
450 &@ac_google_namespace@::LogMessage::SendToLog)
451 #define SYSLOG_DFATAL(counter) \
452 @ac_google_namespace@::LogMessage(__FILE__, __LINE__, @ac_google_namespace@::DFATAL_LEVEL, counter, \
453 &@ac_google_namespace@::LogMessage::SendToSyslogAndLog)
455 #if defined(WIN32) || defined(_WIN32) || defined(__WIN32__) || defined(__CYGWIN__) || defined(__CYGWIN32__)
456 // A very useful logging macro to log windows errors:
457 #define LOG_SYSRESULT(result) \
458 if (FAILED(HRESULT_FROM_WIN32(result))) { \
459 LPSTR message = NULL; \
460 LPSTR msg = reinterpret_cast<LPSTR>(&message); \
461 DWORD message_length = FormatMessageA(FORMAT_MESSAGE_ALLOCATE_BUFFER | \
462 FORMAT_MESSAGE_FROM_SYSTEM, \
463 0, result, 0, msg, 100, NULL); \
464 if (message_length > 0) { \
465 @ac_google_namespace@::LogMessage(__FILE__, __LINE__, @ac_google_namespace@::GLOG_ERROR, 0, \
466 &@ac_google_namespace@::LogMessage::SendToLog).stream() \
467 << reinterpret_cast<const char*>(message); \
468 LocalFree(message); \
473 // We use the preprocessor's merging operator, "##", so that, e.g.,
474 // LOG(INFO) becomes the token GOOGLE_LOG_INFO. There's some funny
475 // subtle difference between ostream member streaming functions (e.g.,
476 // ostream::operator<<(int) and ostream non-member streaming functions
477 // (e.g., ::operator<<(ostream&, string&): it turns out that it's
478 // impossible to stream something like a string directly to an unnamed
479 // ostream. We employ a neat hack by calling the stream() member
480 // function of LogMessage which seems to avoid the problem.
481 #define LOG(severity) COMPACT_GOOGLE_LOG_ ## severity.stream()
482 #define SYSLOG(severity) SYSLOG_ ## severity(0).stream()
484 @ac_google_start_namespace@
486 // They need the definitions of integer types.
487 #include "glog/log_severity.h"
488 #include "glog/vlog_is_on.h"
490 // Initialize google's logging library. You will see the program name
491 // specified by argv0 in log outputs.
492 GOOGLE_GLOG_DLL_DECL void InitGoogleLogging(const char* argv0);
494 // Shutdown google's logging library.
495 GOOGLE_GLOG_DLL_DECL void ShutdownGoogleLogging();
497 // Install a function which will be called after LOG(FATAL).
498 GOOGLE_GLOG_DLL_DECL void InstallFailureFunction(void (*fail_func)());
500 class LogSink; // defined below
502 // If a non-NULL sink pointer is given, we push this message to that sink.
503 // For LOG_TO_SINK we then do normal LOG(severity) logging as well.
504 // This is useful for capturing messages and passing/storing them
505 // somewhere more specific than the global log of the process.
508 // LogSeverity severity;
509 // The cast is to disambiguate NULL arguments.
510 #define LOG_TO_SINK(sink, severity) \
511 @ac_google_namespace@::LogMessage( \
512 __FILE__, __LINE__, \
513 @ac_google_namespace@::GLOG_ ## severity, \
514 static_cast<@ac_google_namespace@::LogSink*>(sink), true).stream()
515 #define LOG_TO_SINK_BUT_NOT_TO_LOGFILE(sink, severity) \
516 @ac_google_namespace@::LogMessage( \
517 __FILE__, __LINE__, \
518 @ac_google_namespace@::GLOG_ ## severity, \
519 static_cast<@ac_google_namespace@::LogSink*>(sink), false).stream()
521 // If a non-NULL string pointer is given, we write this message to that string.
522 // We then do normal LOG(severity) logging as well.
523 // This is useful for capturing messages and storing them somewhere more
524 // specific than the global log of the process.
527 // LogSeverity severity;
528 // The cast is to disambiguate NULL arguments.
529 // NOTE: LOG(severity) expands to LogMessage().stream() for the specified
531 #define LOG_TO_STRING(severity, message) \
532 LOG_TO_STRING_##severity(static_cast<string*>(message)).stream()
534 // If a non-NULL pointer is given, we push the message onto the end
535 // of a vector of strings; otherwise, we report it with LOG(severity).
536 // This is handy for capturing messages and perhaps passing them back
537 // to the caller, rather than reporting them immediately.
539 // LogSeverity severity;
540 // vector<string> *outvec;
541 // The cast is to disambiguate NULL arguments.
542 #define LOG_STRING(severity, outvec) \
543 LOG_TO_STRING_##severity(static_cast<vector<string>*>(outvec)).stream()
545 #define LOG_IF(severity, condition) \
546 !(condition) ? (void) 0 : @ac_google_namespace@::LogMessageVoidify() & LOG(severity)
547 #define SYSLOG_IF(severity, condition) \
548 !(condition) ? (void) 0 : @ac_google_namespace@::LogMessageVoidify() & SYSLOG(severity)
550 #define LOG_ASSERT(condition) \
551 LOG_IF(FATAL, !(condition)) << "Assert failed: " #condition
552 #define SYSLOG_ASSERT(condition) \
553 SYSLOG_IF(FATAL, !(condition)) << "Assert failed: " #condition
555 // CHECK dies with a fatal error if condition is not true. It is *not*
556 // controlled by NDEBUG, so the check will be executed regardless of
557 // compilation mode. Therefore, it is safe to do things like:
558 // CHECK(fp->Write(x) == 4)
559 #define CHECK(condition) \
560 LOG_IF(FATAL, GOOGLE_PREDICT_BRANCH_NOT_TAKEN(!(condition))) \
561 << "Check failed: " #condition " "
563 // A container for a string pointer which can be evaluated to a bool -
564 // true iff the pointer is NULL.
565 struct CheckOpString {
566 CheckOpString(std::string* str) : str_(str) { }
567 // No destructor: if str_ is non-NULL, we're about to LOG(FATAL),
568 // so there's no point in cleaning up str_.
569 operator bool() const {
570 return GOOGLE_PREDICT_BRANCH_NOT_TAKEN(str_ != NULL);
575 // Function is overloaded for integral types to allow static const
576 // integrals declared in classes and not defined to be used as arguments to
577 // CHECK* macros. It's not encouraged though.
579 inline const T& GetReferenceableValue(const T& t) { return t; }
580 inline char GetReferenceableValue(char t) { return t; }
581 inline unsigned char GetReferenceableValue(unsigned char t) { return t; }
582 inline signed char GetReferenceableValue(signed char t) { return t; }
583 inline short GetReferenceableValue(short t) { return t; }
584 inline unsigned short GetReferenceableValue(unsigned short t) { return t; }
585 inline int GetReferenceableValue(int t) { return t; }
586 inline unsigned int GetReferenceableValue(unsigned int t) { return t; }
587 inline long GetReferenceableValue(long t) { return t; }
588 inline unsigned long GetReferenceableValue(unsigned long t) { return t; }
589 inline long long GetReferenceableValue(long long t) { return t; }
590 inline unsigned long long GetReferenceableValue(unsigned long long t) {
594 // This is a dummy class to define the following operator.
595 struct DummyClassToDefineOperator {};
597 @ac_google_end_namespace@
599 // Define global operator<< to declare using ::operator<<.
600 // This declaration will allow use to use CHECK macros for user
601 // defined classes which have operator<< (e.g., stl_logging.h).
602 inline std::ostream& operator<<(
603 std::ostream& out, const google::DummyClassToDefineOperator&) {
607 @ac_google_start_namespace@
609 // Build the error message string.
610 template<class t1, class t2>
611 std::string* MakeCheckOpString(const t1& v1, const t2& v2, const char* names) {
612 // It means that we cannot use stl_logging if compiler doesn't
613 // support using expression for operator.
614 // TODO(hamaji): Figure out a way to fix.
615 #if @ac_cv_cxx_using_operator@
619 ss << names << " (" << v1 << " vs. " << v2 << ")";
620 return new std::string(ss.str(), static_cast<unsigned int>(ss.pcount()));
623 // Helper functions for CHECK_OP macro.
624 // The (int, int) specialization works around the issue that the compiler
625 // will not instantiate the template version of the function on values of
626 // unnamed enum type - see comment below.
627 #define DEFINE_CHECK_OP_IMPL(name, op) \
628 template <class t1, class t2> \
629 inline std::string* Check##name##Impl(const t1& v1, const t2& v2, \
630 const char* names) { \
631 if (v1 op v2) return NULL; \
632 else return MakeCheckOpString(v1, v2, names); \
634 inline std::string* Check##name##Impl(int v1, int v2, const char* names) { \
635 return Check##name##Impl<int, int>(v1, v2, names); \
638 // Use _EQ, _NE, _LE, etc. in case the file including base/logging.h
639 // provides its own #defines for the simpler names EQ, NE, LE, etc.
640 // This happens if, for example, those are used as token names in a
642 DEFINE_CHECK_OP_IMPL(_EQ, ==)
643 DEFINE_CHECK_OP_IMPL(_NE, !=)
644 DEFINE_CHECK_OP_IMPL(_LE, <=)
645 DEFINE_CHECK_OP_IMPL(_LT, < )
646 DEFINE_CHECK_OP_IMPL(_GE, >=)
647 DEFINE_CHECK_OP_IMPL(_GT, > )
648 #undef DEFINE_CHECK_OP_IMPL
650 // Helper macro for binary operators.
651 // Don't use this macro directly in your code, use CHECK_EQ et al below.
653 #if defined(STATIC_ANALYSIS)
654 // Only for static analysis tool to know that it is equivalent to assert
655 #define CHECK_OP_LOG(name, op, val1, val2, log) CHECK((val1) op (val2))
656 #elif !defined(NDEBUG)
657 // In debug mode, avoid constructing CheckOpStrings if possible,
658 // to reduce the overhead of CHECK statments by 2x.
659 // Real DCHECK-heavy tests have seen 1.5x speedups.
661 // The meaning of "string" might be different between now and
662 // when this macro gets invoked (e.g., if someone is experimenting
663 // with other string implementations that get defined after this
664 // file is included). Save the current meaning now and use it
666 typedef std::string _Check_string;
667 #define CHECK_OP_LOG(name, op, val1, val2, log) \
668 while (@ac_google_namespace@::_Check_string* _result = \
669 @ac_google_namespace@::Check##name##Impl( \
670 @ac_google_namespace@::GetReferenceableValue(val1), \
671 @ac_google_namespace@::GetReferenceableValue(val2), \
672 #val1 " " #op " " #val2)) \
673 log(__FILE__, __LINE__, \
674 @ac_google_namespace@::CheckOpString(_result)).stream()
676 // In optimized mode, use CheckOpString to hint to compiler that
677 // the while condition is unlikely.
678 #define CHECK_OP_LOG(name, op, val1, val2, log) \
679 while (@ac_google_namespace@::CheckOpString _result = \
680 @ac_google_namespace@::Check##name##Impl( \
681 @ac_google_namespace@::GetReferenceableValue(val1), \
682 @ac_google_namespace@::GetReferenceableValue(val2), \
683 #val1 " " #op " " #val2)) \
684 log(__FILE__, __LINE__, _result).stream()
685 #endif // STATIC_ANALYSIS, !NDEBUG
687 #if GOOGLE_STRIP_LOG <= 3
688 #define CHECK_OP(name, op, val1, val2) \
689 CHECK_OP_LOG(name, op, val1, val2, @ac_google_namespace@::LogMessageFatal)
691 #define CHECK_OP(name, op, val1, val2) \
692 CHECK_OP_LOG(name, op, val1, val2, @ac_google_namespace@::NullStreamFatal)
693 #endif // STRIP_LOG <= 3
695 // Equality/Inequality checks - compare two values, and log a FATAL message
696 // including the two values when the result is not as expected. The values
697 // must have operator<<(ostream, ...) defined.
699 // You may append to the error message like so:
700 // CHECK_NE(1, 2) << ": The world must be ending!";
702 // We are very careful to ensure that each argument is evaluated exactly
703 // once, and that anything which is legal to pass as a function argument is
704 // legal here. In particular, the arguments may be temporary expressions
705 // which will end up being destroyed at the end of the apparent statement,
707 // CHECK_EQ(string("abc")[1], 'b');
709 // WARNING: These don't compile correctly if one of the arguments is a pointer
710 // and the other is NULL. To work around this, simply static_cast NULL to the
711 // type of the desired pointer.
713 #define CHECK_EQ(val1, val2) CHECK_OP(_EQ, ==, val1, val2)
714 #define CHECK_NE(val1, val2) CHECK_OP(_NE, !=, val1, val2)
715 #define CHECK_LE(val1, val2) CHECK_OP(_LE, <=, val1, val2)
716 #define CHECK_LT(val1, val2) CHECK_OP(_LT, < , val1, val2)
717 #define CHECK_GE(val1, val2) CHECK_OP(_GE, >=, val1, val2)
718 #define CHECK_GT(val1, val2) CHECK_OP(_GT, > , val1, val2)
720 // Check that the input is non NULL. This very useful in constructor
721 // initializer lists.
723 #define CHECK_NOTNULL(val) \
724 @ac_google_namespace@::CheckNotNull(__FILE__, __LINE__, "'" #val "' Must be non NULL", (val))
726 // Helper functions for string comparisons.
727 // To avoid bloat, the definitions are in logging.cc.
728 #define DECLARE_CHECK_STROP_IMPL(func, expected) \
729 GOOGLE_GLOG_DLL_DECL std::string* Check##func##expected##Impl( \
730 const char* s1, const char* s2, const char* names);
731 DECLARE_CHECK_STROP_IMPL(strcmp, true)
732 DECLARE_CHECK_STROP_IMPL(strcmp, false)
733 DECLARE_CHECK_STROP_IMPL(strcasecmp, true)
734 DECLARE_CHECK_STROP_IMPL(strcasecmp, false)
735 #undef DECLARE_CHECK_STROP_IMPL
737 // Helper macro for string comparisons.
738 // Don't use this macro directly in your code, use CHECK_STREQ et al below.
739 #define CHECK_STROP(func, op, expected, s1, s2) \
740 while (@ac_google_namespace@::CheckOpString _result = \
741 @ac_google_namespace@::Check##func##expected##Impl((s1), (s2), \
742 #s1 " " #op " " #s2)) \
743 LOG(FATAL) << *_result.str_
746 // String (char*) equality/inequality checks.
747 // CASE versions are case-insensitive.
749 // Note that "s1" and "s2" may be temporary strings which are destroyed
750 // by the compiler at the end of the current "full expression"
751 // (e.g. CHECK_STREQ(Foo().c_str(), Bar().c_str())).
753 #define CHECK_STREQ(s1, s2) CHECK_STROP(strcmp, ==, true, s1, s2)
754 #define CHECK_STRNE(s1, s2) CHECK_STROP(strcmp, !=, false, s1, s2)
755 #define CHECK_STRCASEEQ(s1, s2) CHECK_STROP(strcasecmp, ==, true, s1, s2)
756 #define CHECK_STRCASENE(s1, s2) CHECK_STROP(strcasecmp, !=, false, s1, s2)
758 #define CHECK_INDEX(I,A) CHECK(I < (sizeof(A)/sizeof(A[0])))
759 #define CHECK_BOUND(B,A) CHECK(B <= (sizeof(A)/sizeof(A[0])))
761 #define CHECK_DOUBLE_EQ(val1, val2) \
763 CHECK_LE((val1), (val2)+0.000000000000001L); \
764 CHECK_GE((val1), (val2)-0.000000000000001L); \
767 #define CHECK_NEAR(val1, val2, margin) \
769 CHECK_LE((val1), (val2)+(margin)); \
770 CHECK_GE((val1), (val2)-(margin)); \
773 // perror()..googly style!
775 // PLOG() and PLOG_IF() and PCHECK() behave exactly like their LOG* and
776 // CHECK equivalents with the addition that they postpend a description
777 // of the current state of errno to their output lines.
779 #define PLOG(severity) GOOGLE_PLOG(severity, 0).stream()
781 #define GOOGLE_PLOG(severity, counter) \
782 @ac_google_namespace@::ErrnoLogMessage( \
783 __FILE__, __LINE__, @ac_google_namespace@::GLOG_ ## severity, counter, \
784 &@ac_google_namespace@::LogMessage::SendToLog)
786 #define PLOG_IF(severity, condition) \
787 !(condition) ? (void) 0 : @ac_google_namespace@::LogMessageVoidify() & PLOG(severity)
789 // A CHECK() macro that postpends errno if the condition is false. E.g.
791 // if (poll(fds, nfds, timeout) == -1) { PCHECK(errno == EINTR); ... }
792 #define PCHECK(condition) \
793 PLOG_IF(FATAL, GOOGLE_PREDICT_BRANCH_NOT_TAKEN(!(condition))) \
794 << "Check failed: " #condition " "
796 // A CHECK() macro that lets you assert the success of a function that
797 // returns -1 and sets errno in case of an error. E.g.
799 // CHECK_ERR(mkdir(path, 0700));
803 // int fd = open(filename, flags); CHECK_ERR(fd) << ": open " << filename;
804 #define CHECK_ERR(invocation) \
805 PLOG_IF(FATAL, GOOGLE_PREDICT_BRANCH_NOT_TAKEN((invocation) == -1)) \
808 // Use macro expansion to create, for each use of LOG_EVERY_N(), static
809 // variables with the __LINE__ expansion as part of the variable name.
810 #define LOG_EVERY_N_VARNAME(base, line) LOG_EVERY_N_VARNAME_CONCAT(base, line)
811 #define LOG_EVERY_N_VARNAME_CONCAT(base, line) base ## line
813 #define LOG_OCCURRENCES LOG_EVERY_N_VARNAME(occurrences_, __LINE__)
814 #define LOG_OCCURRENCES_MOD_N LOG_EVERY_N_VARNAME(occurrences_mod_n_, __LINE__)
816 #define SOME_KIND_OF_LOG_EVERY_N(severity, n, what_to_do) \
817 static int LOG_OCCURRENCES = 0, LOG_OCCURRENCES_MOD_N = 0; \
819 if (++LOG_OCCURRENCES_MOD_N > n) LOG_OCCURRENCES_MOD_N -= n; \
820 if (LOG_OCCURRENCES_MOD_N == 1) \
821 @ac_google_namespace@::LogMessage( \
822 __FILE__, __LINE__, @ac_google_namespace@::GLOG_ ## severity, LOG_OCCURRENCES, \
823 &what_to_do).stream()
825 #define SOME_KIND_OF_LOG_IF_EVERY_N(severity, condition, n, what_to_do) \
826 static int LOG_OCCURRENCES = 0, LOG_OCCURRENCES_MOD_N = 0; \
829 ((LOG_OCCURRENCES_MOD_N=(LOG_OCCURRENCES_MOD_N + 1) % n) == (1 % n))) \
830 @ac_google_namespace@::LogMessage( \
831 __FILE__, __LINE__, @ac_google_namespace@::GLOG_ ## severity, LOG_OCCURRENCES, \
832 &what_to_do).stream()
834 #define SOME_KIND_OF_PLOG_EVERY_N(severity, n, what_to_do) \
835 static int LOG_OCCURRENCES = 0, LOG_OCCURRENCES_MOD_N = 0; \
837 if (++LOG_OCCURRENCES_MOD_N > n) LOG_OCCURRENCES_MOD_N -= n; \
838 if (LOG_OCCURRENCES_MOD_N == 1) \
839 @ac_google_namespace@::ErrnoLogMessage( \
840 __FILE__, __LINE__, @ac_google_namespace@::GLOG_ ## severity, LOG_OCCURRENCES, \
841 &what_to_do).stream()
843 #define SOME_KIND_OF_LOG_FIRST_N(severity, n, what_to_do) \
844 static int LOG_OCCURRENCES = 0; \
845 if (LOG_OCCURRENCES <= n) \
847 if (LOG_OCCURRENCES <= n) \
848 @ac_google_namespace@::LogMessage( \
849 __FILE__, __LINE__, @ac_google_namespace@::GLOG_ ## severity, LOG_OCCURRENCES, \
850 &what_to_do).stream()
852 namespace glog_internal_namespace_ {
854 struct CompileAssert {
857 } // namespace glog_internal_namespace_
859 #define GOOGLE_GLOG_COMPILE_ASSERT(expr, msg) \
860 typedef @ac_google_namespace@::glog_internal_namespace_::CompileAssert<(bool(expr))> msg[bool(expr) ? 1 : -1]
862 #define LOG_EVERY_N(severity, n) \
863 GOOGLE_GLOG_COMPILE_ASSERT(@ac_google_namespace@::GLOG_ ## severity < \
864 @ac_google_namespace@::NUM_SEVERITIES, \
865 INVALID_REQUESTED_LOG_SEVERITY); \
866 SOME_KIND_OF_LOG_EVERY_N(severity, (n), @ac_google_namespace@::LogMessage::SendToLog)
868 #define SYSLOG_EVERY_N(severity, n) \
869 SOME_KIND_OF_LOG_EVERY_N(severity, (n), @ac_google_namespace@::LogMessage::SendToSyslogAndLog)
871 #define PLOG_EVERY_N(severity, n) \
872 SOME_KIND_OF_PLOG_EVERY_N(severity, (n), @ac_google_namespace@::LogMessage::SendToLog)
874 #define LOG_FIRST_N(severity, n) \
875 SOME_KIND_OF_LOG_FIRST_N(severity, (n), @ac_google_namespace@::LogMessage::SendToLog)
877 #define LOG_IF_EVERY_N(severity, condition, n) \
878 SOME_KIND_OF_LOG_IF_EVERY_N(severity, (condition), (n), @ac_google_namespace@::LogMessage::SendToLog)
880 // We want the special COUNTER value available for LOG_EVERY_X()'ed messages
881 enum PRIVATE_Counter {COUNTER};
883 #ifdef GLOG_NO_ABBREVIATED_SEVERITIES
884 // wingdi.h defines ERROR to be 0. When we call LOG(ERROR), it gets
885 // substituted with 0, and it expands to COMPACT_GOOGLE_LOG_0. To allow us
886 // to keep using this syntax, we define this macro to do the same thing
887 // as COMPACT_GOOGLE_LOG_ERROR.
888 #define COMPACT_GOOGLE_LOG_0 COMPACT_GOOGLE_LOG_ERROR
889 #define SYSLOG_0 SYSLOG_ERROR
890 #define LOG_TO_STRING_0 LOG_TO_STRING_ERROR
891 // Needed for LOG_IS_ON(ERROR).
892 const LogSeverity GLOG_0 = GLOG_ERROR;
894 // Users may include windows.h after logging.h without
895 // GLOG_NO_ABBREVIATED_SEVERITIES nor WIN32_LEAN_AND_MEAN.
896 // For this case, we cannot detect if ERROR is defined before users
897 // actually use ERROR. Let's make an undefined symbol to warn users.
898 # define GLOG_ERROR_MSG ERROR_macro_is_defined_Define_GLOG_NO_ABBREVIATED_SEVERITIES_before_including_logging_h_See_the_document_for_detail
899 # define COMPACT_GOOGLE_LOG_0 GLOG_ERROR_MSG
900 # define SYSLOG_0 GLOG_ERROR_MSG
901 # define LOG_TO_STRING_0 GLOG_ERROR_MSG
902 # define GLOG_0 GLOG_ERROR_MSG
905 // Plus some debug-logging macros that get compiled to nothing for production
909 #define DLOG(severity) LOG(severity)
910 #define DVLOG(verboselevel) VLOG(verboselevel)
911 #define DLOG_IF(severity, condition) LOG_IF(severity, condition)
912 #define DLOG_EVERY_N(severity, n) LOG_EVERY_N(severity, n)
913 #define DLOG_IF_EVERY_N(severity, condition, n) \
914 LOG_IF_EVERY_N(severity, condition, n)
915 #define DLOG_ASSERT(condition) LOG_ASSERT(condition)
917 // debug-only checking. not executed in NDEBUG mode.
918 #define DCHECK(condition) CHECK(condition)
919 #define DCHECK_EQ(val1, val2) CHECK_EQ(val1, val2)
920 #define DCHECK_NE(val1, val2) CHECK_NE(val1, val2)
921 #define DCHECK_LE(val1, val2) CHECK_LE(val1, val2)
922 #define DCHECK_LT(val1, val2) CHECK_LT(val1, val2)
923 #define DCHECK_GE(val1, val2) CHECK_GE(val1, val2)
924 #define DCHECK_GT(val1, val2) CHECK_GT(val1, val2)
925 #define DCHECK_NOTNULL(val) CHECK_NOTNULL(val)
926 #define DCHECK_STREQ(str1, str2) CHECK_STREQ(str1, str2)
927 #define DCHECK_STRCASEEQ(str1, str2) CHECK_STRCASEEQ(str1, str2)
928 #define DCHECK_STRNE(str1, str2) CHECK_STRNE(str1, str2)
929 #define DCHECK_STRCASENE(str1, str2) CHECK_STRCASENE(str1, str2)
933 #define DLOG(severity) \
934 true ? (void) 0 : @ac_google_namespace@::LogMessageVoidify() & LOG(severity)
936 #define DVLOG(verboselevel) \
937 (true || !VLOG_IS_ON(verboselevel)) ?\
938 (void) 0 : @ac_google_namespace@::LogMessageVoidify() & LOG(INFO)
940 #define DLOG_IF(severity, condition) \
941 (true || !(condition)) ? (void) 0 : @ac_google_namespace@::LogMessageVoidify() & LOG(severity)
943 #define DLOG_EVERY_N(severity, n) \
944 true ? (void) 0 : @ac_google_namespace@::LogMessageVoidify() & LOG(severity)
946 #define DLOG_IF_EVERY_N(severity, condition, n) \
947 (true || !(condition))? (void) 0 : @ac_google_namespace@::LogMessageVoidify() & LOG(severity)
949 #define DLOG_ASSERT(condition) \
950 true ? (void) 0 : LOG_ASSERT(condition)
952 // MSVC warning C4127: conditional expression is constant
953 #define DCHECK(condition) \
954 GLOG_MSVC_PUSH_DISABLE_WARNING(4127) \
956 GLOG_MSVC_POP_WARNING() CHECK(condition)
958 #define DCHECK_EQ(val1, val2) \
959 GLOG_MSVC_PUSH_DISABLE_WARNING(4127) \
961 GLOG_MSVC_POP_WARNING() CHECK_EQ(val1, val2)
963 #define DCHECK_NE(val1, val2) \
964 GLOG_MSVC_PUSH_DISABLE_WARNING(4127) \
966 GLOG_MSVC_POP_WARNING() CHECK_NE(val1, val2)
968 #define DCHECK_LE(val1, val2) \
969 GLOG_MSVC_PUSH_DISABLE_WARNING(4127) \
971 GLOG_MSVC_POP_WARNING() CHECK_LE(val1, val2)
973 #define DCHECK_LT(val1, val2) \
974 GLOG_MSVC_PUSH_DISABLE_WARNING(4127) \
976 GLOG_MSVC_POP_WARNING() CHECK_LT(val1, val2)
978 #define DCHECK_GE(val1, val2) \
979 GLOG_MSVC_PUSH_DISABLE_WARNING(4127) \
981 GLOG_MSVC_POP_WARNING() CHECK_GE(val1, val2)
983 #define DCHECK_GT(val1, val2) \
984 GLOG_MSVC_PUSH_DISABLE_WARNING(4127) \
986 GLOG_MSVC_POP_WARNING() CHECK_GT(val1, val2)
988 #define DCHECK_NOTNULL(val) (val)
990 #define DCHECK_STREQ(str1, str2) \
991 GLOG_MSVC_PUSH_DISABLE_WARNING(4127) \
993 GLOG_MSVC_POP_WARNING() CHECK_STREQ(str1, str2)
995 #define DCHECK_STRCASEEQ(str1, str2) \
996 GLOG_MSVC_PUSH_DISABLE_WARNING(4127) \
998 GLOG_MSVC_POP_WARNING() CHECK_STRCASEEQ(str1, str2)
1000 #define DCHECK_STRNE(str1, str2) \
1001 GLOG_MSVC_PUSH_DISABLE_WARNING(4127) \
1003 GLOG_MSVC_POP_WARNING() CHECK_STRNE(str1, str2)
1005 #define DCHECK_STRCASENE(str1, str2) \
1006 GLOG_MSVC_PUSH_DISABLE_WARNING(4127) \
1008 GLOG_MSVC_POP_WARNING() CHECK_STRCASENE(str1, str2)
1012 // Log only in verbose mode.
1014 #define VLOG(verboselevel) LOG_IF(INFO, VLOG_IS_ON(verboselevel))
1016 #define VLOG_IF(verboselevel, condition) \
1017 LOG_IF(INFO, (condition) && VLOG_IS_ON(verboselevel))
1019 #define VLOG_EVERY_N(verboselevel, n) \
1020 LOG_IF_EVERY_N(INFO, VLOG_IS_ON(verboselevel), n)
1022 #define VLOG_IF_EVERY_N(verboselevel, condition, n) \
1023 LOG_IF_EVERY_N(INFO, (condition) && VLOG_IS_ON(verboselevel), n)
1026 // This class more or less represents a particular log message. You
1027 // create an instance of LogMessage and then stream stuff to it.
1028 // When you finish streaming to it, ~LogMessage is called and the
1029 // full message gets streamed to the appropriate destination.
1031 // You shouldn't actually use LogMessage's constructor to log things,
1032 // though. You should use the LOG() macro (and variants thereof)
1034 class GOOGLE_GLOG_DLL_DECL LogMessage {
1037 // Passing kNoLogPrefix for the line number disables the
1038 // log-message prefix. Useful for using the LogMessage
1039 // infrastructure as a printing utility. See also the --log_prefix
1040 // flag for controlling the log-message prefix on an
1041 // application-wide basis.
1045 // LogStream inherit from non-DLL-exported class (std::ostrstream)
1046 // and VC++ produces a warning for this situation.
1047 // However, MSDN says "C4275 can be ignored in Microsoft Visual C++
1048 // 2005 if you are deriving from a type in the Standard C++ Library"
1049 // http://msdn.microsoft.com/en-us/library/3tdb471s(VS.80).aspx
1050 // Let's just ignore the warning.
1052 # pragma warning(disable: 4275)
1054 class GOOGLE_GLOG_DLL_DECL LogStream : public std::ostrstream {
1056 # pragma warning(default: 4275)
1059 LogStream(char *buf, int len, int ctr_in)
1060 : ostrstream(buf, len),
1065 int ctr() const { return ctr_; }
1066 void set_ctr(int ctr_in) { ctr_ = ctr_in; }
1067 LogStream* self() const { return self_; }
1070 int ctr_; // Counter hack (for the LOG_EVERY_X() macro)
1071 LogStream *self_; // Consistency check hack
1075 // icc 8 requires this typedef to avoid an internal compiler error.
1076 typedef void (LogMessage::*SendMethod)();
1078 LogMessage(const char* file, int line, LogSeverity severity, int ctr,
1079 SendMethod send_method);
1081 // Two special constructors that generate reduced amounts of code at
1082 // LOG call sites for common cases.
1084 // Used for LOG(INFO): Implied are:
1085 // severity = INFO, ctr = 0, send_method = &LogMessage::SendToLog.
1087 // Using this constructor instead of the more complex constructor above
1088 // saves 19 bytes per call site.
1089 LogMessage(const char* file, int line);
1091 // Used for LOG(severity) where severity != INFO. Implied
1092 // are: ctr = 0, send_method = &LogMessage::SendToLog
1094 // Using this constructor instead of the more complex constructor above
1095 // saves 17 bytes per call site.
1096 LogMessage(const char* file, int line, LogSeverity severity);
1098 // Constructor to log this message to a specified sink (if not NULL).
1099 // Implied are: ctr = 0, send_method = &LogMessage::SendToSinkAndLog if
1100 // also_send_to_log is true, send_method = &LogMessage::SendToSink otherwise.
1101 LogMessage(const char* file, int line, LogSeverity severity, LogSink* sink,
1102 bool also_send_to_log);
1104 // Constructor where we also give a vector<string> pointer
1105 // for storing the messages (if the pointer is not NULL).
1106 // Implied are: ctr = 0, send_method = &LogMessage::SaveOrSendToLog.
1107 LogMessage(const char* file, int line, LogSeverity severity,
1108 std::vector<std::string>* outvec);
1110 // Constructor where we also give a string pointer for storing the
1111 // message (if the pointer is not NULL). Implied are: ctr = 0,
1112 // send_method = &LogMessage::WriteToStringAndLog.
1113 LogMessage(const char* file, int line, LogSeverity severity,
1114 std::string* message);
1116 // A special constructor used for check failures
1117 LogMessage(const char* file, int line, const CheckOpString& result);
1121 // Flush a buffered message to the sink set in the constructor. Always
1122 // called by the destructor, it may also be called from elsewhere if
1123 // needed. Only the first call is actioned; any later ones are ignored.
1126 // An arbitrary limit on the length of a single log message. This
1127 // is so that streaming can be done more efficiently.
1128 static const size_t kMaxLogMessageLen;
1130 // Theses should not be called directly outside of logging.*,
1131 // only passed as SendMethod arguments to other LogMessage methods:
1132 void SendToLog(); // Actually dispatch to the logs
1133 void SendToSyslogAndLog(); // Actually dispatch to syslog and the logs
1135 // Call abort() or similar to perform LOG(FATAL) crash.
1136 static void Fail() @ac_cv___attribute___noreturn@;
1138 std::ostream& stream() { return *(data_->stream_); }
1140 int preserved_errno() const { return data_->preserved_errno_; }
1142 // Must be called without the log_mutex held. (L < log_mutex)
1143 static int64 num_messages(int severity);
1146 // Fully internal SendMethod cases:
1147 void SendToSinkAndLog(); // Send to sink if provided and dispatch to the logs
1148 void SendToSink(); // Send to sink if provided, do nothing otherwise.
1150 // Write to string if provided and dispatch to the logs.
1151 void WriteToStringAndLog();
1153 void SaveOrSendToLog(); // Save to stringvec if provided, else to logs
1155 void Init(const char* file, int line, LogSeverity severity,
1156 void (LogMessage::*send_method)());
1158 // Used to fill in crash information during LOG(FATAL) failures.
1159 void RecordCrashReason(glog_internal_namespace_::CrashReason* reason);
1161 // Counts of messages sent at each priority:
1162 static int64 num_messages_[NUM_SEVERITIES]; // under log_mutex
1164 // We keep the data in a separate struct so that each instance of
1165 // LogMessage uses less stack space.
1166 struct GOOGLE_GLOG_DLL_DECL LogMessageData {
1167 LogMessageData() {};
1169 int preserved_errno_; // preserved errno
1171 char* message_text_; // Complete message text (points to selected buffer)
1172 LogStream* stream_alloc_;
1174 char severity_; // What level is this LogMessage logged at?
1175 int line_; // line number where logging call is.
1176 void (LogMessage::*send_method_)(); // Call this in destructor to send
1177 union { // At most one of these is used: union to keep the size low.
1178 LogSink* sink_; // NULL or sink to send message to
1179 std::vector<std::string>* outvec_; // NULL or vector to push message onto
1180 std::string* message_; // NULL or string to write message into
1182 time_t timestamp_; // Time of creation of LogMessage
1183 struct ::tm tm_time_; // Time of creation of LogMessage
1184 size_t num_prefix_chars_; // # of chars of prefix in this message
1185 size_t num_chars_to_log_; // # of chars of msg to send to log
1186 size_t num_chars_to_syslog_; // # of chars of msg to send to syslog
1187 const char* basename_; // basename of file that called LOG
1188 const char* fullname_; // fullname of file that called LOG
1189 bool has_been_flushed_; // false => data has not been flushed
1190 bool first_fatal_; // true => this was first fatal msg
1194 LogMessageData(const LogMessageData&);
1195 void operator=(const LogMessageData&);
1198 static LogMessageData fatal_msg_data_exclusive_;
1199 static LogMessageData fatal_msg_data_shared_;
1201 LogMessageData* allocated_;
1202 LogMessageData* data_;
1204 friend class LogDestination;
1206 LogMessage(const LogMessage&);
1207 void operator=(const LogMessage&);
1210 // This class happens to be thread-hostile because all instances share
1211 // a single data buffer, but since it can only be created just before
1212 // the process dies, we don't worry so much.
1213 class GOOGLE_GLOG_DLL_DECL LogMessageFatal : public LogMessage {
1215 LogMessageFatal(const char* file, int line);
1216 LogMessageFatal(const char* file, int line, const CheckOpString& result);
1217 ~LogMessageFatal() @ac_cv___attribute___noreturn@;
1220 // A non-macro interface to the log facility; (useful
1221 // when the logging level is not a compile-time constant).
1222 inline void LogAtLevel(int const severity, std::string const &msg) {
1223 LogMessage(__FILE__, __LINE__, severity).stream() << msg;
1226 // A macro alternative of LogAtLevel. New code may want to use this
1227 // version since there are two advantages: 1. this version outputs the
1228 // file name and the line number where this macro is put like other
1229 // LOG macros, 2. this macro can be used as C++ stream.
1230 #define LOG_AT_LEVEL(severity) @ac_google_namespace@::LogMessage(__FILE__, __LINE__, severity).stream()
1232 // A small helper for CHECK_NOTNULL().
1233 template <typename T>
1234 T* CheckNotNull(const char *file, int line, const char *names, T* t) {
1236 LogMessageFatal(file, line, new std::string(names));
1241 // Allow folks to put a counter in the LOG_EVERY_X()'ed messages. This
1242 // only works if ostream is a LogStream. If the ostream is not a
1243 // LogStream you'll get an assert saying as much at runtime.
1244 GOOGLE_GLOG_DLL_DECL std::ostream& operator<<(std::ostream &os,
1245 const PRIVATE_Counter&);
1248 // Derived class for PLOG*() above.
1249 class GOOGLE_GLOG_DLL_DECL ErrnoLogMessage : public LogMessage {
1252 ErrnoLogMessage(const char* file, int line, LogSeverity severity, int ctr,
1253 void (LogMessage::*send_method)());
1255 // Postpends ": strerror(errno) [errno]".
1259 ErrnoLogMessage(const ErrnoLogMessage&);
1260 void operator=(const ErrnoLogMessage&);
1264 // This class is used to explicitly ignore values in the conditional
1265 // logging macros. This avoids compiler warnings like "value computed
1266 // is not used" and "statement has no effect".
1268 class GOOGLE_GLOG_DLL_DECL LogMessageVoidify {
1270 LogMessageVoidify() { }
1271 // This has to be an operator with a precedence lower than << but
1273 void operator&(std::ostream&) { }
1277 // Flushes all log files that contains messages that are at least of
1278 // the specified severity level. Thread-safe.
1279 GOOGLE_GLOG_DLL_DECL void FlushLogFiles(LogSeverity min_severity);
1281 // Flushes all log files that contains messages that are at least of
1282 // the specified severity level. Thread-hostile because it ignores
1283 // locking -- used for catastrophic failures.
1284 GOOGLE_GLOG_DLL_DECL void FlushLogFilesUnsafe(LogSeverity min_severity);
1287 // Set the destination to which a particular severity level of log
1288 // messages is sent. If base_filename is "", it means "don't log this
1289 // severity". Thread-safe.
1291 GOOGLE_GLOG_DLL_DECL void SetLogDestination(LogSeverity severity,
1292 const char* base_filename);
1295 // Set the basename of the symlink to the latest log file at a given
1296 // severity. If symlink_basename is empty, do not make a symlink. If
1297 // you don't call this function, the symlink basename is the
1298 // invocation name of the program. Thread-safe.
1300 GOOGLE_GLOG_DLL_DECL void SetLogSymlink(LogSeverity severity,
1301 const char* symlink_basename);
1304 // Used to send logs to some other kind of destination
1305 // Users should subclass LogSink and override send to do whatever they want.
1306 // Implementations must be thread-safe because a shared instance will
1307 // be called from whichever thread ran the LOG(XXX) line.
1308 class GOOGLE_GLOG_DLL_DECL LogSink {
1312 // Sink's logging logic (message_len is such as to exclude '\n' at the end).
1313 // This method can't use LOG() or CHECK() as logging system mutex(s) are held
1314 // during this call.
1315 virtual void send(LogSeverity severity, const char* full_filename,
1316 const char* base_filename, int line,
1317 const struct ::tm* tm_time,
1318 const char* message, size_t message_len) = 0;
1320 // Redefine this to implement waiting for
1321 // the sink's logging logic to complete.
1322 // It will be called after each send() returns,
1323 // but before that LogMessage exits or crashes.
1324 // By default this function does nothing.
1325 // Using this function one can implement complex logic for send()
1326 // that itself involves logging; and do all this w/o causing deadlocks and
1327 // inconsistent rearrangement of log messages.
1328 // E.g. if a LogSink has thread-specific actions, the send() method
1329 // can simply add the message to a queue and wake up another thread that
1330 // handles real logging while itself making some LOG() calls;
1331 // WaitTillSent() can be implemented to wait for that logic to complete.
1332 // See our unittest for an example.
1333 virtual void WaitTillSent();
1335 // Returns the normal text output of the log message.
1336 // Can be useful to implement send().
1337 static std::string ToString(LogSeverity severity, const char* file, int line,
1338 const struct ::tm* tm_time,
1339 const char* message, size_t message_len);
1342 // Add or remove a LogSink as a consumer of logging data. Thread-safe.
1343 GOOGLE_GLOG_DLL_DECL void AddLogSink(LogSink *destination);
1344 GOOGLE_GLOG_DLL_DECL void RemoveLogSink(LogSink *destination);
1347 // Specify an "extension" added to the filename specified via
1348 // SetLogDestination. This applies to all severity levels. It's
1349 // often used to append the port we're listening on to the logfile
1350 // name. Thread-safe.
1352 GOOGLE_GLOG_DLL_DECL void SetLogFilenameExtension(
1353 const char* filename_extension);
1356 // Make it so that all log messages of at least a particular severity
1357 // are logged to stderr (in addition to logging to the usual log
1358 // file(s)). Thread-safe.
1360 GOOGLE_GLOG_DLL_DECL void SetStderrLogging(LogSeverity min_severity);
1363 // Make it so that all log messages go only to stderr. Thread-safe.
1365 GOOGLE_GLOG_DLL_DECL void LogToStderr();
1368 // Make it so that all log messages of at least a particular severity are
1369 // logged via email to a list of addresses (in addition to logging to the
1370 // usual log file(s)). The list of addresses is just a string containing
1371 // the email addresses to send to (separated by spaces, say). Thread-safe.
1373 GOOGLE_GLOG_DLL_DECL void SetEmailLogging(LogSeverity min_severity,
1374 const char* addresses);
1376 // A simple function that sends email. dest is a commma-separated
1377 // list of addressess. Thread-safe.
1378 GOOGLE_GLOG_DLL_DECL bool SendEmail(const char *dest,
1379 const char *subject, const char *body);
1381 GOOGLE_GLOG_DLL_DECL const std::vector<std::string>& GetLoggingDirectories();
1383 // For tests only: Clear the internal [cached] list of logging directories to
1384 // force a refresh the next time GetLoggingDirectories is called.
1386 void TestOnly_ClearLoggingDirectoriesList();
1388 // Returns a set of existing temporary directories, which will be a
1389 // subset of the directories returned by GetLogginDirectories().
1391 GOOGLE_GLOG_DLL_DECL void GetExistingTempDirectories(
1392 std::vector<std::string>* list);
1394 // Print any fatal message again -- useful to call from signal handler
1395 // so that the last thing in the output is the fatal message.
1396 // Thread-hostile, but a race is unlikely.
1397 GOOGLE_GLOG_DLL_DECL void ReprintFatalMessage();
1399 // Truncate a log file that may be the append-only output of multiple
1400 // processes and hence can't simply be renamed/reopened (typically a
1401 // stdout/stderr). If the file "path" is > "limit" bytes, copy the
1402 // last "keep" bytes to offset 0 and truncate the rest. Since we could
1403 // be racing with other writers, this approach has the potential to
1404 // lose very small amounts of data. For security, only follow symlinks
1405 // if the path is /proc/self/fd/*
1406 GOOGLE_GLOG_DLL_DECL void TruncateLogFile(const char *path,
1407 int64 limit, int64 keep);
1409 // Truncate stdout and stderr if they are over the value specified by
1410 // --max_log_size; keep the final 1MB. This function has the same
1411 // race condition as TruncateLogFile.
1412 GOOGLE_GLOG_DLL_DECL void TruncateStdoutStderr();
1414 // Return the string representation of the provided LogSeverity level.
1416 GOOGLE_GLOG_DLL_DECL const char* GetLogSeverityName(LogSeverity severity);
1418 // ---------------------------------------------------------------------
1419 // Implementation details that are not useful to most clients
1420 // ---------------------------------------------------------------------
1422 // A Logger is the interface used by logging modules to emit entries
1423 // to a log. A typical implementation will dump formatted data to a
1424 // sequence of files. We also provide interfaces that will forward
1425 // the data to another thread so that the invoker never blocks.
1426 // Implementations should be thread-safe since the logging system
1427 // will write to them from multiple threads.
1431 class GOOGLE_GLOG_DLL_DECL Logger {
1435 // Writes "message[0,message_len-1]" corresponding to an event that
1436 // occurred at "timestamp". If "force_flush" is true, the log file
1437 // is flushed immediately.
1439 // The input message has already been formatted as deemed
1440 // appropriate by the higher level logging facility. For example,
1441 // textual log messages already contain timestamps, and the
1442 // file:linenumber header.
1443 virtual void Write(bool force_flush,
1445 const char* message,
1446 int message_len) = 0;
1448 // Flush any buffered messages
1449 virtual void Flush() = 0;
1451 // Get the current LOG file size.
1452 // The returned value is approximate since some
1453 // logged data may not have been flushed to disk yet.
1454 virtual uint32 LogSize() = 0;
1457 // Get the logger for the specified severity level. The logger
1458 // remains the property of the logging module and should not be
1459 // deleted by the caller. Thread-safe.
1460 extern GOOGLE_GLOG_DLL_DECL Logger* GetLogger(LogSeverity level);
1462 // Set the logger for the specified severity level. The logger
1463 // becomes the property of the logging module and should not
1464 // be deleted by the caller. Thread-safe.
1465 extern GOOGLE_GLOG_DLL_DECL void SetLogger(LogSeverity level, Logger* logger);
1469 // glibc has traditionally implemented two incompatible versions of
1470 // strerror_r(). There is a poorly defined convention for picking the
1471 // version that we want, but it is not clear whether it even works with
1472 // all versions of glibc.
1473 // So, instead, we provide this wrapper that automatically detects the
1474 // version that is in use, and then implements POSIX semantics.
1475 // N.B. In addition to what POSIX says, we also guarantee that "buf" will
1476 // be set to an empty string, if this function failed. This means, in most
1477 // cases, you do not need to check the error code and you can directly
1478 // use the value of "buf". It will never have an undefined value.
1479 GOOGLE_GLOG_DLL_DECL int posix_strerror_r(int err, char *buf, size_t len);
1482 // A class for which we define operator<<, which does nothing.
1483 class GOOGLE_GLOG_DLL_DECL NullStream : public LogMessage::LogStream {
1485 // Initialize the LogStream so the messages can be written somewhere
1486 // (they'll never be actually displayed). This will be needed if a
1487 // NullStream& is implicitly converted to LogStream&, in which case
1488 // the overloaded NullStream::operator<< will not be invoked.
1489 NullStream() : LogMessage::LogStream(message_buffer_, 1, 0) { }
1490 NullStream(const char* /*file*/, int /*line*/,
1491 const CheckOpString& /*result*/) :
1492 LogMessage::LogStream(message_buffer_, 1, 0) { }
1493 NullStream &stream() { return *this; }
1495 // A very short buffer for messages (which we discard anyway). This
1496 // will be needed if NullStream& converted to LogStream& (e.g. as a
1497 // result of a conditional expression).
1498 char message_buffer_[2];
1501 // Do nothing. This operator is inline, allowing the message to be
1502 // compiled away. The message will not be compiled away if we do
1503 // something like (flag ? LOG(INFO) : LOG(ERROR)) << message; when
1504 // SKIP_LOG=WARNING. In those cases, NullStream will be implicitly
1505 // converted to LogStream and the message will be computed and then
1506 // quietly discarded.
1508 inline NullStream& operator<<(NullStream &str, const T &) { return str; }
1510 // Similar to NullStream, but aborts the program (without stack
1511 // trace), like LogMessageFatal.
1512 class GOOGLE_GLOG_DLL_DECL NullStreamFatal : public NullStream {
1514 NullStreamFatal() { }
1515 NullStreamFatal(const char* file, int line, const CheckOpString& result) :
1516 NullStream(file, line, result) { }
1517 @ac_cv___attribute___noreturn@ ~NullStreamFatal() { _exit(1); }
1520 // Install a signal handler that will dump signal information and a stack
1521 // trace when the program crashes on certain signals. We'll install the
1522 // signal handler for the following signals.
1524 // SIGSEGV, SIGILL, SIGFPE, SIGABRT, SIGBUS, and SIGTERM.
1526 // By default, the signal handler will write the failure dump to the
1527 // standard error. You can customize the destination by installing your
1528 // own writer function by InstallFailureWriter() below.
1530 // Note on threading:
1532 // The function should be called before threads are created, if you want
1533 // to use the failure signal handler for all threads. The stack trace
1534 // will be shown only for the thread that receives the signal. In other
1535 // words, stack traces of other threads won't be shown.
1536 GOOGLE_GLOG_DLL_DECL void InstallFailureSignalHandler();
1538 // Installs a function that is used for writing the failure dump. "data"
1539 // is the pointer to the beginning of a message to be written, and "size"
1540 // is the size of the message. You should not expect the data is
1541 // terminated with '\0'.
1542 GOOGLE_GLOG_DLL_DECL void InstallFailureWriter(
1543 void (*writer)(const char* data, int size));
1545 @ac_google_end_namespace@
1547 #undef GLOG_MSVC_PUSH_DISABLE_WARNING
1548 #undef GLOG_MSVC_POP_WARNING
1550 #endif // _LOGGING_H_