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.
46 #if @ac_cv_have_unistd_h@
52 #define GLOG_MSVC_PUSH_DISABLE_WARNING(n) __pragma(warning(push)) \
53 __pragma(warning(disable:n))
54 #define GLOG_MSVC_POP_WARNING() __pragma(warning(pop))
56 #define GLOG_MSVC_PUSH_DISABLE_WARNING(n)
57 #define GLOG_MSVC_POP_WARNING()
60 // Annoying stuff for windows -- makes sure clients can import these functions
61 #ifndef GOOGLE_GLOG_DLL_DECL
62 # if defined(_WIN32) && !defined(__CYGWIN__)
63 # define GOOGLE_GLOG_DLL_DECL __declspec(dllimport)
65 # define GOOGLE_GLOG_DLL_DECL
69 // We care a lot about number of bits things take up. Unfortunately,
70 // systems define their bit-specific ints in a lot of different ways.
71 // We use our own way, and have a typedef to get there.
72 // Note: these commands below may look like "#if 1" or "#if 0", but
73 // that's because they were constructed that way at ./configure time.
74 // Look at logging.h.in to see how they're calculated (based on your config).
75 #if @ac_cv_have_stdint_h@
76 #include <stdint.h> // the normal place uint16_t is defined
78 #if @ac_cv_have_systypes_h@
79 #include <sys/types.h> // the normal place u_int16_t is defined
81 #if @ac_cv_have_inttypes_h@
82 #include <inttypes.h> // a third place for uint16_t or u_int16_t
85 #if @ac_cv_have_libgflags@
86 #include <gflags/gflags.h>
89 @ac_google_start_namespace@
91 #if @ac_cv_have_uint16_t@ // the C99 format
92 typedef int32_t int32;
93 typedef uint32_t uint32;
94 typedef int64_t int64;
95 typedef uint64_t uint64;
96 #elif @ac_cv_have_u_int16_t@ // the BSD format
97 typedef int32_t int32;
98 typedef u_int32_t uint32;
99 typedef int64_t int64;
100 typedef u_int64_t uint64;
101 #elif @ac_cv_have___uint16@ // the windows (vc7) format
102 typedef __int32 int32;
103 typedef unsigned __int32 uint32;
104 typedef __int64 int64;
105 typedef unsigned __int64 uint64;
107 #error Do not know how to define a 32-bit integer quantity on your system
110 @ac_google_end_namespace@
112 // The global value of GOOGLE_STRIP_LOG. All the messages logged to
113 // LOG(XXX) with severity less than GOOGLE_STRIP_LOG will not be displayed.
114 // If it can be determined at compile time that the message will not be
115 // printed, the statement will be compiled out.
117 // Example: to strip out all INFO and WARNING messages, use the value
118 // of 2 below. To make an exception for WARNING messages from a single
119 // file, add "#define GOOGLE_STRIP_LOG 1" to that file _before_ including
121 #ifndef GOOGLE_STRIP_LOG
122 #define GOOGLE_STRIP_LOG 0
125 // GCC can be told that a certain branch is not likely to be taken (for
126 // instance, a CHECK failure), and use that information in static analysis.
127 // Giving it this information can help it optimize for the common case in
128 // the absence of better information (ie. -fprofile-arcs).
130 #ifndef GOOGLE_PREDICT_BRANCH_NOT_TAKEN
131 #if @ac_cv_have___builtin_expect@
132 #define GOOGLE_PREDICT_BRANCH_NOT_TAKEN(x) (__builtin_expect(x, 0))
134 #define GOOGLE_PREDICT_BRANCH_NOT_TAKEN(x) x
138 #ifndef GOOGLE_PREDICT_FALSE
139 #if @ac_cv_have___builtin_expect@
140 #define GOOGLE_PREDICT_FALSE(x) (__builtin_expect(x, 0))
142 #define GOOGLE_PREDICT_FALSE(x) x
146 #ifndef GOOGLE_PREDICT_TRUE
147 #if @ac_cv_have___builtin_expect@
148 #define GOOGLE_PREDICT_TRUE(x) (__builtin_expect(!!(x), 1))
150 #define GOOGLE_PREDICT_TRUE(x) x
155 // Make a bunch of macros for logging. The way to log things is to stream
156 // things to LOG(<a particular severity level>). E.g.,
158 // LOG(INFO) << "Found " << num_cookies << " cookies";
160 // You can capture log messages in a string, rather than reporting them
163 // vector<string> errors;
164 // LOG_STRING(ERROR, &errors) << "Couldn't parse cookie #" << cookie_num;
166 // This pushes back the new error onto 'errors'; if given a NULL pointer,
167 // it reports the error via LOG(ERROR).
169 // You can also do conditional logging:
171 // LOG_IF(INFO, num_cookies > 10) << "Got lots of cookies";
173 // You can also do occasional logging (log every n'th occurrence of an
176 // LOG_EVERY_N(INFO, 10) << "Got the " << google::COUNTER << "th cookie";
178 // The above will cause log messages to be output on the 1st, 11th, 21st, ...
179 // times it is executed. Note that the special google::COUNTER value is used
180 // to identify which repetition is happening.
182 // You can also do occasional conditional logging (log every n'th
183 // occurrence of an event, when condition is satisfied):
185 // LOG_IF_EVERY_N(INFO, (size > 1024), 10) << "Got the " << google::COUNTER
186 // << "th big cookie";
188 // You can log messages the first N times your code executes a line. E.g.
190 // LOG_FIRST_N(INFO, 20) << "Got the " << google::COUNTER << "th cookie";
192 // Outputs log messages for the first 20 times it is executed.
194 // Analogous SYSLOG, SYSLOG_IF, and SYSLOG_EVERY_N macros are available.
195 // These log to syslog as well as to the normal logs. If you use these at
196 // all, you need to be aware that syslog can drastically reduce performance,
197 // especially if it is configured for remote logging! Don't use these
198 // unless you fully understand this and have a concrete need to use them.
199 // Even then, try to minimize your use of them.
201 // There are also "debug mode" logging macros like the ones above:
203 // DLOG(INFO) << "Found cookies";
205 // DLOG_IF(INFO, num_cookies > 10) << "Got lots of cookies";
207 // DLOG_EVERY_N(INFO, 10) << "Got the " << google::COUNTER << "th cookie";
209 // All "debug mode" logging is compiled away to nothing for non-debug mode
214 // LOG_ASSERT(assertion);
215 // DLOG_ASSERT(assertion);
217 // which is syntactic sugar for {,D}LOG_IF(FATAL, assert fails) << assertion;
219 // There are "verbose level" logging macros. They look like
221 // VLOG(1) << "I'm printed when you run the program with --v=1 or more";
222 // VLOG(2) << "I'm printed when you run the program with --v=2 or more";
224 // These always log at the INFO log level (when they log at all).
225 // The verbose logging can also be turned on module-by-module. For instance,
226 // --vmodule=mapreduce=2,file=1,gfs*=3 --v=0
228 // a. VLOG(2) and lower messages to be printed from mapreduce.{h,cc}
229 // b. VLOG(1) and lower messages to be printed from file.{h,cc}
230 // c. VLOG(3) and lower messages to be printed from files prefixed with "gfs"
231 // d. VLOG(0) and lower messages to be printed from elsewhere
233 // The wildcarding functionality shown by (c) supports both '*' (match
234 // 0 or more characters) and '?' (match any single character) wildcards.
236 // There's also VLOG_IS_ON(n) "verbose level" condition macro. To be used as
238 // if (VLOG_IS_ON(2)) {
239 // // do some logging preparation and logging
240 // // that can't be accomplished with just VLOG(2) << ...;
243 // There are also VLOG_IF, VLOG_EVERY_N and VLOG_IF_EVERY_N "verbose level"
244 // condition macros for sample cases, when some extra computation and
245 // preparation for logs is not needed.
246 // VLOG_IF(1, (size > 1024))
247 // << "I'm printed when size is more than 1024 and when you run the "
248 // "program with --v=1 or more";
249 // VLOG_EVERY_N(1, 10)
250 // << "I'm printed every 10th occurrence, and when you run the program "
251 // "with --v=1 or more. Present occurence is " << google::COUNTER;
252 // VLOG_IF_EVERY_N(1, (size > 1024), 10)
253 // << "I'm printed on every 10th occurence of case when size is more "
254 // " than 1024, when you run the program with --v=1 or more. ";
255 // "Present occurence is " << google::COUNTER;
257 // The supported severity levels for macros that allow you to specify one
258 // are (in increasing order of severity) INFO, WARNING, ERROR, and FATAL.
259 // Note that messages of a given severity are logged not only in the
260 // logfile for that severity, but also in all logfiles of lower severity.
261 // E.g., a message of severity FATAL will be logged to the logfiles of
262 // severity FATAL, ERROR, WARNING, and INFO.
264 // There is also the special severity of DFATAL, which logs FATAL in
265 // debug mode, ERROR in normal mode.
267 // Very important: logging a message at the FATAL severity level causes
268 // the program to terminate (after the message is logged).
270 // Unless otherwise specified, logs will be written to the filename
271 // "<program name>.<hostname>.<user name>.log.<severity level>.", followed
272 // by the date, time, and pid (you can't prevent the date, time, and pid
273 // from being in the filename).
275 // The logging code takes two flags:
276 // --v=# set the verbose level
277 // --logtostderr log all the messages to stderr instead of to logfiles
279 // LOG LINE PREFIX FORMAT
281 // Log lines have this form:
283 // Lmmdd hh:mm:ss.uuuuuu threadid file:line] msg...
285 // where the fields are defined as follows:
287 // L A single character, representing the log level
289 // mm The month (zero padded; ie May is '05')
290 // dd The day (zero padded)
291 // hh:mm:ss.uuuuuu Time in hours, minutes and fractional seconds
292 // threadid The space-padded thread ID as returned by GetTID()
293 // (this matches the PID on Linux)
294 // file The file name
295 // line The line number
296 // msg The user-supplied message
300 // I1103 11:57:31.739339 24395 google.cc:2341] Command line: ./some_prog
301 // I1103 11:57:31.739403 24395 google.cc:2342] Process id 24395
303 // NOTE: although the microseconds are useful for comparing events on
304 // a single machine, clocks on different machines may not be well
305 // synchronized. Hence, use caution when comparing the low bits of
306 // timestamps from different machines.
308 #ifndef DECLARE_VARIABLE
309 #define MUST_UNDEF_GFLAGS_DECLARE_MACROS
310 #define DECLARE_VARIABLE(type, shorttype, name, tn) \
311 namespace fL##shorttype { \
312 extern GOOGLE_GLOG_DLL_DECL type FLAGS_##name; \
314 using fL##shorttype::FLAGS_##name
316 // bool specialization
317 #define DECLARE_bool(name) \
318 DECLARE_VARIABLE(bool, B, name, bool)
320 // int32 specialization
321 #define DECLARE_int32(name) \
322 DECLARE_VARIABLE(@ac_google_namespace@::int32, I, name, int32)
324 // Special case for string, because we have to specify the namespace
325 // std::string, which doesn't play nicely with our FLAG__namespace hackery.
326 #define DECLARE_string(name) \
328 extern GOOGLE_GLOG_DLL_DECL std::string& FLAGS_##name; \
330 using fLS::FLAGS_##name
333 // Set whether log messages go to stderr instead of logfiles
334 DECLARE_bool(logtostderr);
336 // Set whether log messages go to stderr in addition to logfiles.
337 DECLARE_bool(alsologtostderr);
339 // Set color messages logged to stderr (if supported by terminal).
340 DECLARE_bool(colorlogtostderr);
342 // Log messages at a level >= this flag are automatically sent to
343 // stderr in addition to log files.
344 DECLARE_int32(stderrthreshold);
346 // Set whether the log prefix should be prepended to each line of output.
347 DECLARE_bool(log_prefix);
349 // Log messages at a level <= this flag are buffered.
350 // Log messages at a higher level are flushed immediately.
351 DECLARE_int32(logbuflevel);
353 // Sets the maximum number of seconds which logs may be buffered for.
354 DECLARE_int32(logbufsecs);
356 // Log suppression level: messages logged at a lower level than this
358 DECLARE_int32(minloglevel);
360 // If specified, logfiles are written into this directory instead of the
361 // default logging directory.
362 DECLARE_string(log_dir);
364 // Set the log file mode.
365 DECLARE_int32(logfile_mode);
367 // Sets the path of the directory into which to put additional links
369 DECLARE_string(log_link);
371 DECLARE_int32(v); // in vlog_is_on.cc
373 // Sets the maximum log file size (in MB).
374 DECLARE_int32(max_log_size);
376 // Sets whether to avoid logging to the disk if the disk is full.
377 DECLARE_bool(stop_logging_if_full_disk);
379 #ifdef MUST_UNDEF_GFLAGS_DECLARE_MACROS
380 #undef MUST_UNDEF_GFLAGS_DECLARE_MACROS
381 #undef DECLARE_VARIABLE
384 #undef DECLARE_string
387 // Log messages below the GOOGLE_STRIP_LOG level will be compiled away for
388 // security reasons. See LOG(severtiy) below.
390 // A few definitions of macros that don't generate much code. Since
391 // LOG(INFO) and its ilk are used all over our code, it's
392 // better to have compact code for these operations.
394 #if GOOGLE_STRIP_LOG == 0
395 #define COMPACT_GOOGLE_LOG_INFO @ac_google_namespace@::LogMessage( \
397 #define LOG_TO_STRING_INFO(message) @ac_google_namespace@::LogMessage( \
398 __FILE__, __LINE__, @ac_google_namespace@::GLOG_INFO, message)
400 #define COMPACT_GOOGLE_LOG_INFO @ac_google_namespace@::NullStream()
401 #define LOG_TO_STRING_INFO(message) @ac_google_namespace@::NullStream()
404 #if GOOGLE_STRIP_LOG <= 1
405 #define COMPACT_GOOGLE_LOG_WARNING @ac_google_namespace@::LogMessage( \
406 __FILE__, __LINE__, @ac_google_namespace@::GLOG_WARNING)
407 #define LOG_TO_STRING_WARNING(message) @ac_google_namespace@::LogMessage( \
408 __FILE__, __LINE__, @ac_google_namespace@::GLOG_WARNING, message)
410 #define COMPACT_GOOGLE_LOG_WARNING @ac_google_namespace@::NullStream()
411 #define LOG_TO_STRING_WARNING(message) @ac_google_namespace@::NullStream()
414 #if GOOGLE_STRIP_LOG <= 2
415 #define COMPACT_GOOGLE_LOG_ERROR @ac_google_namespace@::LogMessage( \
416 __FILE__, __LINE__, @ac_google_namespace@::GLOG_ERROR)
417 #define LOG_TO_STRING_ERROR(message) @ac_google_namespace@::LogMessage( \
418 __FILE__, __LINE__, @ac_google_namespace@::GLOG_ERROR, message)
420 #define COMPACT_GOOGLE_LOG_ERROR @ac_google_namespace@::NullStream()
421 #define LOG_TO_STRING_ERROR(message) @ac_google_namespace@::NullStream()
424 #if GOOGLE_STRIP_LOG <= 3
425 #define COMPACT_GOOGLE_LOG_FATAL @ac_google_namespace@::LogMessageFatal( \
427 #define LOG_TO_STRING_FATAL(message) @ac_google_namespace@::LogMessage( \
428 __FILE__, __LINE__, @ac_google_namespace@::GLOG_FATAL, message)
430 #define COMPACT_GOOGLE_LOG_FATAL @ac_google_namespace@::NullStreamFatal()
431 #define LOG_TO_STRING_FATAL(message) @ac_google_namespace@::NullStreamFatal()
434 // For DFATAL, we want to use LogMessage (as opposed to
435 // LogMessageFatal), to be consistent with the original behavior.
437 #define COMPACT_GOOGLE_LOG_DFATAL COMPACT_GOOGLE_LOG_ERROR
438 #elif GOOGLE_STRIP_LOG <= 3
439 #define COMPACT_GOOGLE_LOG_DFATAL @ac_google_namespace@::LogMessage( \
440 __FILE__, __LINE__, @ac_google_namespace@::GLOG_FATAL)
442 #define COMPACT_GOOGLE_LOG_DFATAL @ac_google_namespace@::NullStreamFatal()
445 #define GOOGLE_LOG_INFO(counter) @ac_google_namespace@::LogMessage(__FILE__, __LINE__, @ac_google_namespace@::GLOG_INFO, counter, &@ac_google_namespace@::LogMessage::SendToLog)
446 #define SYSLOG_INFO(counter) \
447 @ac_google_namespace@::LogMessage(__FILE__, __LINE__, @ac_google_namespace@::GLOG_INFO, counter, \
448 &@ac_google_namespace@::LogMessage::SendToSyslogAndLog)
449 #define GOOGLE_LOG_WARNING(counter) \
450 @ac_google_namespace@::LogMessage(__FILE__, __LINE__, @ac_google_namespace@::GLOG_WARNING, counter, \
451 &@ac_google_namespace@::LogMessage::SendToLog)
452 #define SYSLOG_WARNING(counter) \
453 @ac_google_namespace@::LogMessage(__FILE__, __LINE__, @ac_google_namespace@::GLOG_WARNING, counter, \
454 &@ac_google_namespace@::LogMessage::SendToSyslogAndLog)
455 #define GOOGLE_LOG_ERROR(counter) \
456 @ac_google_namespace@::LogMessage(__FILE__, __LINE__, @ac_google_namespace@::GLOG_ERROR, counter, \
457 &@ac_google_namespace@::LogMessage::SendToLog)
458 #define SYSLOG_ERROR(counter) \
459 @ac_google_namespace@::LogMessage(__FILE__, __LINE__, @ac_google_namespace@::GLOG_ERROR, counter, \
460 &@ac_google_namespace@::LogMessage::SendToSyslogAndLog)
461 #define GOOGLE_LOG_FATAL(counter) \
462 @ac_google_namespace@::LogMessage(__FILE__, __LINE__, @ac_google_namespace@::GLOG_FATAL, counter, \
463 &@ac_google_namespace@::LogMessage::SendToLog)
464 #define SYSLOG_FATAL(counter) \
465 @ac_google_namespace@::LogMessage(__FILE__, __LINE__, @ac_google_namespace@::GLOG_FATAL, counter, \
466 &@ac_google_namespace@::LogMessage::SendToSyslogAndLog)
467 #define GOOGLE_LOG_DFATAL(counter) \
468 @ac_google_namespace@::LogMessage(__FILE__, __LINE__, @ac_google_namespace@::DFATAL_LEVEL, counter, \
469 &@ac_google_namespace@::LogMessage::SendToLog)
470 #define SYSLOG_DFATAL(counter) \
471 @ac_google_namespace@::LogMessage(__FILE__, __LINE__, @ac_google_namespace@::DFATAL_LEVEL, counter, \
472 &@ac_google_namespace@::LogMessage::SendToSyslogAndLog)
474 #if defined(WIN32) || defined(_WIN32) || defined(__WIN32__) || defined(__CYGWIN__) || defined(__CYGWIN32__)
475 // A very useful logging macro to log windows errors:
476 #define LOG_SYSRESULT(result) \
477 if (FAILED(HRESULT_FROM_WIN32(result))) { \
478 LPSTR message = NULL; \
479 LPSTR msg = reinterpret_cast<LPSTR>(&message); \
480 DWORD message_length = FormatMessageA(FORMAT_MESSAGE_ALLOCATE_BUFFER | \
481 FORMAT_MESSAGE_FROM_SYSTEM, \
482 0, result, 0, msg, 100, NULL); \
483 if (message_length > 0) { \
484 @ac_google_namespace@::LogMessage(__FILE__, __LINE__, @ac_google_namespace@::GLOG_ERROR, 0, \
485 &@ac_google_namespace@::LogMessage::SendToLog).stream() \
486 << reinterpret_cast<const char*>(message); \
487 LocalFree(message); \
492 // We use the preprocessor's merging operator, "##", so that, e.g.,
493 // LOG(INFO) becomes the token GOOGLE_LOG_INFO. There's some funny
494 // subtle difference between ostream member streaming functions (e.g.,
495 // ostream::operator<<(int) and ostream non-member streaming functions
496 // (e.g., ::operator<<(ostream&, string&): it turns out that it's
497 // impossible to stream something like a string directly to an unnamed
498 // ostream. We employ a neat hack by calling the stream() member
499 // function of LogMessage which seems to avoid the problem.
500 #define LOG(severity) COMPACT_GOOGLE_LOG_ ## severity.stream()
501 #define SYSLOG(severity) SYSLOG_ ## severity(0).stream()
503 @ac_google_start_namespace@
505 // They need the definitions of integer types.
506 #include "glog/log_severity.h"
507 #include "glog/vlog_is_on.h"
509 // Initialize google's logging library. You will see the program name
510 // specified by argv0 in log outputs.
511 GOOGLE_GLOG_DLL_DECL void InitGoogleLogging(const char* argv0);
513 // Shutdown google's logging library.
514 GOOGLE_GLOG_DLL_DECL void ShutdownGoogleLogging();
516 // Install a function which will be called after LOG(FATAL).
517 GOOGLE_GLOG_DLL_DECL void InstallFailureFunction(void (*fail_func)());
519 class LogSink; // defined below
521 // If a non-NULL sink pointer is given, we push this message to that sink.
522 // For LOG_TO_SINK we then do normal LOG(severity) logging as well.
523 // This is useful for capturing messages and passing/storing them
524 // somewhere more specific than the global log of the process.
527 // LogSeverity severity;
528 // The cast is to disambiguate NULL arguments.
529 #define LOG_TO_SINK(sink, severity) \
530 @ac_google_namespace@::LogMessage( \
531 __FILE__, __LINE__, \
532 @ac_google_namespace@::GLOG_ ## severity, \
533 static_cast<@ac_google_namespace@::LogSink*>(sink), true).stream()
534 #define LOG_TO_SINK_BUT_NOT_TO_LOGFILE(sink, severity) \
535 @ac_google_namespace@::LogMessage( \
536 __FILE__, __LINE__, \
537 @ac_google_namespace@::GLOG_ ## severity, \
538 static_cast<@ac_google_namespace@::LogSink*>(sink), false).stream()
540 // If a non-NULL string pointer is given, we write this message to that string.
541 // We then do normal LOG(severity) logging as well.
542 // This is useful for capturing messages and storing them somewhere more
543 // specific than the global log of the process.
546 // LogSeverity severity;
547 // The cast is to disambiguate NULL arguments.
548 // NOTE: LOG(severity) expands to LogMessage().stream() for the specified
550 #define LOG_TO_STRING(severity, message) \
551 LOG_TO_STRING_##severity(static_cast<string*>(message)).stream()
553 // If a non-NULL pointer is given, we push the message onto the end
554 // of a vector of strings; otherwise, we report it with LOG(severity).
555 // This is handy for capturing messages and perhaps passing them back
556 // to the caller, rather than reporting them immediately.
558 // LogSeverity severity;
559 // vector<string> *outvec;
560 // The cast is to disambiguate NULL arguments.
561 #define LOG_STRING(severity, outvec) \
562 LOG_TO_STRING_##severity(static_cast<std::vector<std::string>*>(outvec)).stream()
564 #define LOG_IF(severity, condition) \
565 !(condition) ? (void) 0 : @ac_google_namespace@::LogMessageVoidify() & LOG(severity)
566 #define SYSLOG_IF(severity, condition) \
567 !(condition) ? (void) 0 : @ac_google_namespace@::LogMessageVoidify() & SYSLOG(severity)
569 #define LOG_ASSERT(condition) \
570 LOG_IF(FATAL, !(condition)) << "Assert failed: " #condition
571 #define SYSLOG_ASSERT(condition) \
572 SYSLOG_IF(FATAL, !(condition)) << "Assert failed: " #condition
574 // CHECK dies with a fatal error if condition is not true. It is *not*
575 // controlled by NDEBUG, so the check will be executed regardless of
576 // compilation mode. Therefore, it is safe to do things like:
577 // CHECK(fp->Write(x) == 4)
578 #define CHECK(condition) \
579 LOG_IF(FATAL, GOOGLE_PREDICT_BRANCH_NOT_TAKEN(!(condition))) \
580 << "Check failed: " #condition " "
582 // A container for a string pointer which can be evaluated to a bool -
583 // true iff the pointer is NULL.
584 struct CheckOpString {
585 CheckOpString(std::string* str) : str_(str) { }
586 // No destructor: if str_ is non-NULL, we're about to LOG(FATAL),
587 // so there's no point in cleaning up str_.
588 operator bool() const {
589 return GOOGLE_PREDICT_BRANCH_NOT_TAKEN(str_ != NULL);
594 // Function is overloaded for integral types to allow static const
595 // integrals declared in classes and not defined to be used as arguments to
596 // CHECK* macros. It's not encouraged though.
598 inline const T& GetReferenceableValue(const T& t) { return t; }
599 inline char GetReferenceableValue(char t) { return t; }
600 inline unsigned char GetReferenceableValue(unsigned char t) { return t; }
601 inline signed char GetReferenceableValue(signed char t) { return t; }
602 inline short GetReferenceableValue(short t) { return t; }
603 inline unsigned short GetReferenceableValue(unsigned short t) { return t; }
604 inline int GetReferenceableValue(int t) { return t; }
605 inline unsigned int GetReferenceableValue(unsigned int t) { return t; }
606 inline long GetReferenceableValue(long t) { return t; }
607 inline unsigned long GetReferenceableValue(unsigned long t) { return t; }
608 inline long long GetReferenceableValue(long long t) { return t; }
609 inline unsigned long long GetReferenceableValue(unsigned long long t) {
613 // This is a dummy class to define the following operator.
614 struct DummyClassToDefineOperator {};
616 @ac_google_end_namespace@
618 // Define global operator<< to declare using ::operator<<.
619 // This declaration will allow use to use CHECK macros for user
620 // defined classes which have operator<< (e.g., stl_logging.h).
621 inline std::ostream& operator<<(
622 std::ostream& out, const google::DummyClassToDefineOperator&) {
626 @ac_google_start_namespace@
628 // This formats a value for a failing CHECK_XX statement. Ordinarily,
629 // it uses the definition for operator<<, with a few special cases below.
630 template <typename T>
631 inline void MakeCheckOpValueString(std::ostream* os, const T& v) {
635 // Overrides for char types provide readable values for unprintable
637 template <> GOOGLE_GLOG_DLL_DECL
638 void MakeCheckOpValueString(std::ostream* os, const char& v);
639 template <> GOOGLE_GLOG_DLL_DECL
640 void MakeCheckOpValueString(std::ostream* os, const signed char& v);
641 template <> GOOGLE_GLOG_DLL_DECL
642 void MakeCheckOpValueString(std::ostream* os, const unsigned char& v);
644 // Build the error message string. Specify no inlining for code size.
645 template <typename T1, typename T2>
646 std::string* MakeCheckOpString(const T1& v1, const T2& v2, const char* exprtext)
647 @ac_cv___attribute___noinline@;
652 // If "s" is less than base_logging::INFO, returns base_logging::INFO.
653 // If "s" is greater than base_logging::FATAL, returns
654 // base_logging::ERROR. Otherwise, returns "s".
655 LogSeverity NormalizeSeverity(LogSeverity s);
657 } // namespace internal
659 // A helper class for formatting "expr (V1 vs. V2)" in a CHECK_XX
660 // statement. See MakeCheckOpString for sample usage. Other
661 // approaches were considered: use of a template method (e.g.,
662 // base::BuildCheckOpString(exprtext, base::Print<T1>, &v1,
663 // base::Print<T2>, &v2), however this approach has complications
664 // related to volatile arguments and function-pointer arguments).
665 class GOOGLE_GLOG_DLL_DECL CheckOpMessageBuilder {
667 // Inserts "exprtext" and " (" to the stream.
668 explicit CheckOpMessageBuilder(const char *exprtext);
669 // Deletes "stream_".
670 ~CheckOpMessageBuilder();
671 // For inserting the first variable.
672 std::ostream* ForVar1() { return stream_; }
673 // For inserting the second variable (adds an intermediate " vs. ").
674 std::ostream* ForVar2();
675 // Get the result (inserts the closing ")").
676 std::string* NewString();
679 std::ostringstream *stream_;
684 template <typename T1, typename T2>
685 std::string* MakeCheckOpString(const T1& v1, const T2& v2, const char* exprtext) {
686 base::CheckOpMessageBuilder comb(exprtext);
687 MakeCheckOpValueString(comb.ForVar1(), v1);
688 MakeCheckOpValueString(comb.ForVar2(), v2);
689 return comb.NewString();
692 // Helper functions for CHECK_OP macro.
693 // The (int, int) specialization works around the issue that the compiler
694 // will not instantiate the template version of the function on values of
695 // unnamed enum type - see comment below.
696 #define DEFINE_CHECK_OP_IMPL(name, op) \
697 template <typename T1, typename T2> \
698 inline std::string* name##Impl(const T1& v1, const T2& v2, \
699 const char* exprtext) { \
700 if (GOOGLE_PREDICT_TRUE(v1 op v2)) return NULL; \
701 else return MakeCheckOpString(v1, v2, exprtext); \
703 inline std::string* name##Impl(int v1, int v2, const char* exprtext) { \
704 return name##Impl<int, int>(v1, v2, exprtext); \
707 // We use the full name Check_EQ, Check_NE, etc. in case the file including
708 // base/logging.h provides its own #defines for the simpler names EQ, NE, etc.
709 // This happens if, for example, those are used as token names in a
711 DEFINE_CHECK_OP_IMPL(Check_EQ, ==) // Compilation error with CHECK_EQ(NULL, x)?
712 DEFINE_CHECK_OP_IMPL(Check_NE, !=) // Use CHECK(x == NULL) instead.
713 DEFINE_CHECK_OP_IMPL(Check_LE, <=)
714 DEFINE_CHECK_OP_IMPL(Check_LT, < )
715 DEFINE_CHECK_OP_IMPL(Check_GE, >=)
716 DEFINE_CHECK_OP_IMPL(Check_GT, > )
717 #undef DEFINE_CHECK_OP_IMPL
719 // Helper macro for binary operators.
720 // Don't use this macro directly in your code, use CHECK_EQ et al below.
722 #if defined(STATIC_ANALYSIS)
723 // Only for static analysis tool to know that it is equivalent to assert
724 #define CHECK_OP_LOG(name, op, val1, val2, log) CHECK((val1) op (val2))
725 #elif !defined(NDEBUG)
726 // In debug mode, avoid constructing CheckOpStrings if possible,
727 // to reduce the overhead of CHECK statments by 2x.
728 // Real DCHECK-heavy tests have seen 1.5x speedups.
730 // The meaning of "string" might be different between now and
731 // when this macro gets invoked (e.g., if someone is experimenting
732 // with other string implementations that get defined after this
733 // file is included). Save the current meaning now and use it
735 typedef std::string _Check_string;
736 #define CHECK_OP_LOG(name, op, val1, val2, log) \
737 while (@ac_google_namespace@::_Check_string* _result = \
738 @ac_google_namespace@::Check##name##Impl( \
739 @ac_google_namespace@::GetReferenceableValue(val1), \
740 @ac_google_namespace@::GetReferenceableValue(val2), \
741 #val1 " " #op " " #val2)) \
742 log(__FILE__, __LINE__, \
743 @ac_google_namespace@::CheckOpString(_result)).stream()
745 // In optimized mode, use CheckOpString to hint to compiler that
746 // the while condition is unlikely.
747 #define CHECK_OP_LOG(name, op, val1, val2, log) \
748 while (@ac_google_namespace@::CheckOpString _result = \
749 @ac_google_namespace@::Check##name##Impl( \
750 @ac_google_namespace@::GetReferenceableValue(val1), \
751 @ac_google_namespace@::GetReferenceableValue(val2), \
752 #val1 " " #op " " #val2)) \
753 log(__FILE__, __LINE__, _result).stream()
754 #endif // STATIC_ANALYSIS, !NDEBUG
756 #if GOOGLE_STRIP_LOG <= 3
757 #define CHECK_OP(name, op, val1, val2) \
758 CHECK_OP_LOG(name, op, val1, val2, @ac_google_namespace@::LogMessageFatal)
760 #define CHECK_OP(name, op, val1, val2) \
761 CHECK_OP_LOG(name, op, val1, val2, @ac_google_namespace@::NullStreamFatal)
762 #endif // STRIP_LOG <= 3
764 // Equality/Inequality checks - compare two values, and log a FATAL message
765 // including the two values when the result is not as expected. The values
766 // must have operator<<(ostream, ...) defined.
768 // You may append to the error message like so:
769 // CHECK_NE(1, 2) << ": The world must be ending!";
771 // We are very careful to ensure that each argument is evaluated exactly
772 // once, and that anything which is legal to pass as a function argument is
773 // legal here. In particular, the arguments may be temporary expressions
774 // which will end up being destroyed at the end of the apparent statement,
776 // CHECK_EQ(string("abc")[1], 'b');
778 // WARNING: These don't compile correctly if one of the arguments is a pointer
779 // and the other is NULL. To work around this, simply static_cast NULL to the
780 // type of the desired pointer.
782 #define CHECK_EQ(val1, val2) CHECK_OP(_EQ, ==, val1, val2)
783 #define CHECK_NE(val1, val2) CHECK_OP(_NE, !=, val1, val2)
784 #define CHECK_LE(val1, val2) CHECK_OP(_LE, <=, val1, val2)
785 #define CHECK_LT(val1, val2) CHECK_OP(_LT, < , val1, val2)
786 #define CHECK_GE(val1, val2) CHECK_OP(_GE, >=, val1, val2)
787 #define CHECK_GT(val1, val2) CHECK_OP(_GT, > , val1, val2)
789 // Check that the input is non NULL. This very useful in constructor
790 // initializer lists.
792 #define CHECK_NOTNULL(val) \
793 @ac_google_namespace@::CheckNotNull(__FILE__, __LINE__, "'" #val "' Must be non NULL", (val))
795 // Helper functions for string comparisons.
796 // To avoid bloat, the definitions are in logging.cc.
797 #define DECLARE_CHECK_STROP_IMPL(func, expected) \
798 GOOGLE_GLOG_DLL_DECL std::string* Check##func##expected##Impl( \
799 const char* s1, const char* s2, const char* names);
800 DECLARE_CHECK_STROP_IMPL(strcmp, true)
801 DECLARE_CHECK_STROP_IMPL(strcmp, false)
802 DECLARE_CHECK_STROP_IMPL(strcasecmp, true)
803 DECLARE_CHECK_STROP_IMPL(strcasecmp, false)
804 #undef DECLARE_CHECK_STROP_IMPL
806 // Helper macro for string comparisons.
807 // Don't use this macro directly in your code, use CHECK_STREQ et al below.
808 #define CHECK_STROP(func, op, expected, s1, s2) \
809 while (@ac_google_namespace@::CheckOpString _result = \
810 @ac_google_namespace@::Check##func##expected##Impl((s1), (s2), \
811 #s1 " " #op " " #s2)) \
812 LOG(FATAL) << *_result.str_
815 // String (char*) equality/inequality checks.
816 // CASE versions are case-insensitive.
818 // Note that "s1" and "s2" may be temporary strings which are destroyed
819 // by the compiler at the end of the current "full expression"
820 // (e.g. CHECK_STREQ(Foo().c_str(), Bar().c_str())).
822 #define CHECK_STREQ(s1, s2) CHECK_STROP(strcmp, ==, true, s1, s2)
823 #define CHECK_STRNE(s1, s2) CHECK_STROP(strcmp, !=, false, s1, s2)
824 #define CHECK_STRCASEEQ(s1, s2) CHECK_STROP(strcasecmp, ==, true, s1, s2)
825 #define CHECK_STRCASENE(s1, s2) CHECK_STROP(strcasecmp, !=, false, s1, s2)
827 #define CHECK_INDEX(I,A) CHECK(I < (sizeof(A)/sizeof(A[0])))
828 #define CHECK_BOUND(B,A) CHECK(B <= (sizeof(A)/sizeof(A[0])))
830 #define CHECK_DOUBLE_EQ(val1, val2) \
832 CHECK_LE((val1), (val2)+0.000000000000001L); \
833 CHECK_GE((val1), (val2)-0.000000000000001L); \
836 #define CHECK_NEAR(val1, val2, margin) \
838 CHECK_LE((val1), (val2)+(margin)); \
839 CHECK_GE((val1), (val2)-(margin)); \
842 // perror()..googly style!
844 // PLOG() and PLOG_IF() and PCHECK() behave exactly like their LOG* and
845 // CHECK equivalents with the addition that they postpend a description
846 // of the current state of errno to their output lines.
848 #define PLOG(severity) GOOGLE_PLOG(severity, 0).stream()
850 #define GOOGLE_PLOG(severity, counter) \
851 @ac_google_namespace@::ErrnoLogMessage( \
852 __FILE__, __LINE__, @ac_google_namespace@::GLOG_ ## severity, counter, \
853 &@ac_google_namespace@::LogMessage::SendToLog)
855 #define PLOG_IF(severity, condition) \
856 !(condition) ? (void) 0 : @ac_google_namespace@::LogMessageVoidify() & PLOG(severity)
858 // A CHECK() macro that postpends errno if the condition is false. E.g.
860 // if (poll(fds, nfds, timeout) == -1) { PCHECK(errno == EINTR); ... }
861 #define PCHECK(condition) \
862 PLOG_IF(FATAL, GOOGLE_PREDICT_BRANCH_NOT_TAKEN(!(condition))) \
863 << "Check failed: " #condition " "
865 // A CHECK() macro that lets you assert the success of a function that
866 // returns -1 and sets errno in case of an error. E.g.
868 // CHECK_ERR(mkdir(path, 0700));
872 // int fd = open(filename, flags); CHECK_ERR(fd) << ": open " << filename;
873 #define CHECK_ERR(invocation) \
874 PLOG_IF(FATAL, GOOGLE_PREDICT_BRANCH_NOT_TAKEN((invocation) == -1)) \
877 // Use macro expansion to create, for each use of LOG_EVERY_N(), static
878 // variables with the __LINE__ expansion as part of the variable name.
879 #define LOG_EVERY_N_VARNAME(base, line) LOG_EVERY_N_VARNAME_CONCAT(base, line)
880 #define LOG_EVERY_N_VARNAME_CONCAT(base, line) base ## line
882 #define LOG_OCCURRENCES LOG_EVERY_N_VARNAME(occurrences_, __LINE__)
883 #define LOG_OCCURRENCES_MOD_N LOG_EVERY_N_VARNAME(occurrences_mod_n_, __LINE__)
885 #define SOME_KIND_OF_LOG_EVERY_N(severity, n, what_to_do) \
886 static int LOG_OCCURRENCES = 0, LOG_OCCURRENCES_MOD_N = 0; \
888 if (++LOG_OCCURRENCES_MOD_N > n) LOG_OCCURRENCES_MOD_N -= n; \
889 if (LOG_OCCURRENCES_MOD_N == 1) \
890 @ac_google_namespace@::LogMessage( \
891 __FILE__, __LINE__, @ac_google_namespace@::GLOG_ ## severity, LOG_OCCURRENCES, \
892 &what_to_do).stream()
894 #define SOME_KIND_OF_LOG_IF_EVERY_N(severity, condition, n, what_to_do) \
895 static int LOG_OCCURRENCES = 0, LOG_OCCURRENCES_MOD_N = 0; \
898 ((LOG_OCCURRENCES_MOD_N=(LOG_OCCURRENCES_MOD_N + 1) % n) == (1 % n))) \
899 @ac_google_namespace@::LogMessage( \
900 __FILE__, __LINE__, @ac_google_namespace@::GLOG_ ## severity, LOG_OCCURRENCES, \
901 &what_to_do).stream()
903 #define SOME_KIND_OF_PLOG_EVERY_N(severity, n, what_to_do) \
904 static int LOG_OCCURRENCES = 0, LOG_OCCURRENCES_MOD_N = 0; \
906 if (++LOG_OCCURRENCES_MOD_N > n) LOG_OCCURRENCES_MOD_N -= n; \
907 if (LOG_OCCURRENCES_MOD_N == 1) \
908 @ac_google_namespace@::ErrnoLogMessage( \
909 __FILE__, __LINE__, @ac_google_namespace@::GLOG_ ## severity, LOG_OCCURRENCES, \
910 &what_to_do).stream()
912 #define SOME_KIND_OF_LOG_FIRST_N(severity, n, what_to_do) \
913 static int LOG_OCCURRENCES = 0; \
914 if (LOG_OCCURRENCES <= n) \
916 if (LOG_OCCURRENCES <= n) \
917 @ac_google_namespace@::LogMessage( \
918 __FILE__, __LINE__, @ac_google_namespace@::GLOG_ ## severity, LOG_OCCURRENCES, \
919 &what_to_do).stream()
921 namespace glog_internal_namespace_ {
923 struct CompileAssert {
926 } // namespace glog_internal_namespace_
928 #define GOOGLE_GLOG_COMPILE_ASSERT(expr, msg) \
929 typedef @ac_google_namespace@::glog_internal_namespace_::CompileAssert<(bool(expr))> msg[bool(expr) ? 1 : -1]
931 #define LOG_EVERY_N(severity, n) \
932 GOOGLE_GLOG_COMPILE_ASSERT(@ac_google_namespace@::GLOG_ ## severity < \
933 @ac_google_namespace@::NUM_SEVERITIES, \
934 INVALID_REQUESTED_LOG_SEVERITY); \
935 SOME_KIND_OF_LOG_EVERY_N(severity, (n), @ac_google_namespace@::LogMessage::SendToLog)
937 #define SYSLOG_EVERY_N(severity, n) \
938 SOME_KIND_OF_LOG_EVERY_N(severity, (n), @ac_google_namespace@::LogMessage::SendToSyslogAndLog)
940 #define PLOG_EVERY_N(severity, n) \
941 SOME_KIND_OF_PLOG_EVERY_N(severity, (n), @ac_google_namespace@::LogMessage::SendToLog)
943 #define LOG_FIRST_N(severity, n) \
944 SOME_KIND_OF_LOG_FIRST_N(severity, (n), @ac_google_namespace@::LogMessage::SendToLog)
946 #define LOG_IF_EVERY_N(severity, condition, n) \
947 SOME_KIND_OF_LOG_IF_EVERY_N(severity, (condition), (n), @ac_google_namespace@::LogMessage::SendToLog)
949 // We want the special COUNTER value available for LOG_EVERY_X()'ed messages
950 enum PRIVATE_Counter {COUNTER};
952 #ifdef GLOG_NO_ABBREVIATED_SEVERITIES
953 // wingdi.h defines ERROR to be 0. When we call LOG(ERROR), it gets
954 // substituted with 0, and it expands to COMPACT_GOOGLE_LOG_0. To allow us
955 // to keep using this syntax, we define this macro to do the same thing
956 // as COMPACT_GOOGLE_LOG_ERROR.
957 #define COMPACT_GOOGLE_LOG_0 COMPACT_GOOGLE_LOG_ERROR
958 #define SYSLOG_0 SYSLOG_ERROR
959 #define LOG_TO_STRING_0 LOG_TO_STRING_ERROR
960 // Needed for LOG_IS_ON(ERROR).
961 const LogSeverity GLOG_0 = GLOG_ERROR;
963 // Users may include windows.h after logging.h without
964 // GLOG_NO_ABBREVIATED_SEVERITIES nor WIN32_LEAN_AND_MEAN.
965 // For this case, we cannot detect if ERROR is defined before users
966 // actually use ERROR. Let's make an undefined symbol to warn users.
967 # define GLOG_ERROR_MSG ERROR_macro_is_defined_Define_GLOG_NO_ABBREVIATED_SEVERITIES_before_including_logging_h_See_the_document_for_detail
968 # define COMPACT_GOOGLE_LOG_0 GLOG_ERROR_MSG
969 # define SYSLOG_0 GLOG_ERROR_MSG
970 # define LOG_TO_STRING_0 GLOG_ERROR_MSG
971 # define GLOG_0 GLOG_ERROR_MSG
974 // Plus some debug-logging macros that get compiled to nothing for production
978 #define DLOG(severity) LOG(severity)
979 #define DVLOG(verboselevel) VLOG(verboselevel)
980 #define DLOG_IF(severity, condition) LOG_IF(severity, condition)
981 #define DLOG_EVERY_N(severity, n) LOG_EVERY_N(severity, n)
982 #define DLOG_IF_EVERY_N(severity, condition, n) \
983 LOG_IF_EVERY_N(severity, condition, n)
984 #define DLOG_ASSERT(condition) LOG_ASSERT(condition)
986 // debug-only checking. not executed in NDEBUG mode.
987 #define DCHECK(condition) CHECK(condition)
988 #define DCHECK_EQ(val1, val2) CHECK_EQ(val1, val2)
989 #define DCHECK_NE(val1, val2) CHECK_NE(val1, val2)
990 #define DCHECK_LE(val1, val2) CHECK_LE(val1, val2)
991 #define DCHECK_LT(val1, val2) CHECK_LT(val1, val2)
992 #define DCHECK_GE(val1, val2) CHECK_GE(val1, val2)
993 #define DCHECK_GT(val1, val2) CHECK_GT(val1, val2)
994 #define DCHECK_NOTNULL(val) CHECK_NOTNULL(val)
995 #define DCHECK_STREQ(str1, str2) CHECK_STREQ(str1, str2)
996 #define DCHECK_STRCASEEQ(str1, str2) CHECK_STRCASEEQ(str1, str2)
997 #define DCHECK_STRNE(str1, str2) CHECK_STRNE(str1, str2)
998 #define DCHECK_STRCASENE(str1, str2) CHECK_STRCASENE(str1, str2)
1002 #define DLOG(severity) \
1003 true ? (void) 0 : @ac_google_namespace@::LogMessageVoidify() & LOG(severity)
1005 #define DVLOG(verboselevel) \
1006 (true || !VLOG_IS_ON(verboselevel)) ?\
1007 (void) 0 : @ac_google_namespace@::LogMessageVoidify() & LOG(INFO)
1009 #define DLOG_IF(severity, condition) \
1010 (true || !(condition)) ? (void) 0 : @ac_google_namespace@::LogMessageVoidify() & LOG(severity)
1012 #define DLOG_EVERY_N(severity, n) \
1013 true ? (void) 0 : @ac_google_namespace@::LogMessageVoidify() & LOG(severity)
1015 #define DLOG_IF_EVERY_N(severity, condition, n) \
1016 (true || !(condition))? (void) 0 : @ac_google_namespace@::LogMessageVoidify() & LOG(severity)
1018 #define DLOG_ASSERT(condition) \
1019 true ? (void) 0 : LOG_ASSERT(condition)
1021 // MSVC warning C4127: conditional expression is constant
1022 #define DCHECK(condition) \
1023 GLOG_MSVC_PUSH_DISABLE_WARNING(4127) \
1025 GLOG_MSVC_POP_WARNING() CHECK(condition)
1027 #define DCHECK_EQ(val1, val2) \
1028 GLOG_MSVC_PUSH_DISABLE_WARNING(4127) \
1030 GLOG_MSVC_POP_WARNING() CHECK_EQ(val1, val2)
1032 #define DCHECK_NE(val1, val2) \
1033 GLOG_MSVC_PUSH_DISABLE_WARNING(4127) \
1035 GLOG_MSVC_POP_WARNING() CHECK_NE(val1, val2)
1037 #define DCHECK_LE(val1, val2) \
1038 GLOG_MSVC_PUSH_DISABLE_WARNING(4127) \
1040 GLOG_MSVC_POP_WARNING() CHECK_LE(val1, val2)
1042 #define DCHECK_LT(val1, val2) \
1043 GLOG_MSVC_PUSH_DISABLE_WARNING(4127) \
1045 GLOG_MSVC_POP_WARNING() CHECK_LT(val1, val2)
1047 #define DCHECK_GE(val1, val2) \
1048 GLOG_MSVC_PUSH_DISABLE_WARNING(4127) \
1050 GLOG_MSVC_POP_WARNING() CHECK_GE(val1, val2)
1052 #define DCHECK_GT(val1, val2) \
1053 GLOG_MSVC_PUSH_DISABLE_WARNING(4127) \
1055 GLOG_MSVC_POP_WARNING() CHECK_GT(val1, val2)
1057 // You may see warnings in release mode if you don't use the return
1058 // value of DCHECK_NOTNULL. Please just use DCHECK for such cases.
1059 #define DCHECK_NOTNULL(val) (val)
1061 #define DCHECK_STREQ(str1, str2) \
1062 GLOG_MSVC_PUSH_DISABLE_WARNING(4127) \
1064 GLOG_MSVC_POP_WARNING() CHECK_STREQ(str1, str2)
1066 #define DCHECK_STRCASEEQ(str1, str2) \
1067 GLOG_MSVC_PUSH_DISABLE_WARNING(4127) \
1069 GLOG_MSVC_POP_WARNING() CHECK_STRCASEEQ(str1, str2)
1071 #define DCHECK_STRNE(str1, str2) \
1072 GLOG_MSVC_PUSH_DISABLE_WARNING(4127) \
1074 GLOG_MSVC_POP_WARNING() CHECK_STRNE(str1, str2)
1076 #define DCHECK_STRCASENE(str1, str2) \
1077 GLOG_MSVC_PUSH_DISABLE_WARNING(4127) \
1079 GLOG_MSVC_POP_WARNING() CHECK_STRCASENE(str1, str2)
1083 // Log only in verbose mode.
1085 #define VLOG(verboselevel) LOG_IF(INFO, VLOG_IS_ON(verboselevel))
1087 #define VLOG_IF(verboselevel, condition) \
1088 LOG_IF(INFO, (condition) && VLOG_IS_ON(verboselevel))
1090 #define VLOG_EVERY_N(verboselevel, n) \
1091 LOG_IF_EVERY_N(INFO, VLOG_IS_ON(verboselevel), n)
1093 #define VLOG_IF_EVERY_N(verboselevel, condition, n) \
1094 LOG_IF_EVERY_N(INFO, (condition) && VLOG_IS_ON(verboselevel), n)
1096 namespace base_logging {
1098 // LogMessage::LogStream is a std::ostream backed by this streambuf.
1099 // This class ignores overflow and leaves two bytes at the end of the
1100 // buffer to allow for a '\n' and '\0'.
1101 class GOOGLE_GLOG_DLL_DECL LogStreamBuf : public std::streambuf {
1103 // REQUIREMENTS: "len" must be >= 2 to account for the '\n' and '\n'.
1104 LogStreamBuf(char *buf, int len) {
1105 setp(buf, buf + len - 2);
1107 // This effectively ignores overflow.
1108 virtual int_type overflow(int_type ch) {
1112 // Legacy public ostrstream method.
1113 size_t pcount() const { return pptr() - pbase(); }
1114 char* pbase() const { return std::streambuf::pbase(); }
1117 } // namespace base_logging
1120 // This class more or less represents a particular log message. You
1121 // create an instance of LogMessage and then stream stuff to it.
1122 // When you finish streaming to it, ~LogMessage is called and the
1123 // full message gets streamed to the appropriate destination.
1125 // You shouldn't actually use LogMessage's constructor to log things,
1126 // though. You should use the LOG() macro (and variants thereof)
1128 class GOOGLE_GLOG_DLL_DECL LogMessage {
1131 // Passing kNoLogPrefix for the line number disables the
1132 // log-message prefix. Useful for using the LogMessage
1133 // infrastructure as a printing utility. See also the --log_prefix
1134 // flag for controlling the log-message prefix on an
1135 // application-wide basis.
1139 // LogStream inherit from non-DLL-exported class (std::ostrstream)
1140 // and VC++ produces a warning for this situation.
1141 // However, MSDN says "C4275 can be ignored in Microsoft Visual C++
1142 // 2005 if you are deriving from a type in the Standard C++ Library"
1143 // http://msdn.microsoft.com/en-us/library/3tdb471s(VS.80).aspx
1144 // Let's just ignore the warning.
1146 # pragma warning(disable: 4275)
1148 class GOOGLE_GLOG_DLL_DECL LogStream : public std::ostream {
1150 # pragma warning(default: 4275)
1153 LogStream(char *buf, int len, int ctr)
1154 : std::ostream(NULL),
1155 streambuf_(buf, len),
1161 int ctr() const { return ctr_; }
1162 void set_ctr(int ctr) { ctr_ = ctr; }
1163 LogStream* self() const { return self_; }
1165 // Legacy std::streambuf methods.
1166 size_t pcount() const { return streambuf_.pcount(); }
1167 char* pbase() const { return streambuf_.pbase(); }
1168 char* str() const { return pbase(); }
1171 LogStream(const LogStream&);
1172 LogStream& operator=(const LogStream&);
1173 base_logging::LogStreamBuf streambuf_;
1174 int ctr_; // Counter hack (for the LOG_EVERY_X() macro)
1175 LogStream *self_; // Consistency check hack
1179 // icc 8 requires this typedef to avoid an internal compiler error.
1180 typedef void (LogMessage::*SendMethod)();
1182 LogMessage(const char* file, int line, LogSeverity severity, int ctr,
1183 SendMethod send_method);
1185 // Two special constructors that generate reduced amounts of code at
1186 // LOG call sites for common cases.
1188 // Used for LOG(INFO): Implied are:
1189 // severity = INFO, ctr = 0, send_method = &LogMessage::SendToLog.
1191 // Using this constructor instead of the more complex constructor above
1192 // saves 19 bytes per call site.
1193 LogMessage(const char* file, int line);
1195 // Used for LOG(severity) where severity != INFO. Implied
1196 // are: ctr = 0, send_method = &LogMessage::SendToLog
1198 // Using this constructor instead of the more complex constructor above
1199 // saves 17 bytes per call site.
1200 LogMessage(const char* file, int line, LogSeverity severity);
1202 // Constructor to log this message to a specified sink (if not NULL).
1203 // Implied are: ctr = 0, send_method = &LogMessage::SendToSinkAndLog if
1204 // also_send_to_log is true, send_method = &LogMessage::SendToSink otherwise.
1205 LogMessage(const char* file, int line, LogSeverity severity, LogSink* sink,
1206 bool also_send_to_log);
1208 // Constructor where we also give a vector<string> pointer
1209 // for storing the messages (if the pointer is not NULL).
1210 // Implied are: ctr = 0, send_method = &LogMessage::SaveOrSendToLog.
1211 LogMessage(const char* file, int line, LogSeverity severity,
1212 std::vector<std::string>* outvec);
1214 // Constructor where we also give a string pointer for storing the
1215 // message (if the pointer is not NULL). Implied are: ctr = 0,
1216 // send_method = &LogMessage::WriteToStringAndLog.
1217 LogMessage(const char* file, int line, LogSeverity severity,
1218 std::string* message);
1220 // A special constructor used for check failures
1221 LogMessage(const char* file, int line, const CheckOpString& result);
1225 // Flush a buffered message to the sink set in the constructor. Always
1226 // called by the destructor, it may also be called from elsewhere if
1227 // needed. Only the first call is actioned; any later ones are ignored.
1230 // An arbitrary limit on the length of a single log message. This
1231 // is so that streaming can be done more efficiently.
1232 static const size_t kMaxLogMessageLen;
1234 // Theses should not be called directly outside of logging.*,
1235 // only passed as SendMethod arguments to other LogMessage methods:
1236 void SendToLog(); // Actually dispatch to the logs
1237 void SendToSyslogAndLog(); // Actually dispatch to syslog and the logs
1239 // Call abort() or similar to perform LOG(FATAL) crash.
1240 static void @ac_cv___attribute___noreturn@ Fail();
1242 std::ostream& stream();
1244 int preserved_errno() const;
1246 // Must be called without the log_mutex held. (L < log_mutex)
1247 static int64 num_messages(int severity);
1249 struct LogMessageData;
1252 // Fully internal SendMethod cases:
1253 void SendToSinkAndLog(); // Send to sink if provided and dispatch to the logs
1254 void SendToSink(); // Send to sink if provided, do nothing otherwise.
1256 // Write to string if provided and dispatch to the logs.
1257 void WriteToStringAndLog();
1259 void SaveOrSendToLog(); // Save to stringvec if provided, else to logs
1261 void Init(const char* file, int line, LogSeverity severity,
1262 void (LogMessage::*send_method)());
1264 // Used to fill in crash information during LOG(FATAL) failures.
1265 void RecordCrashReason(glog_internal_namespace_::CrashReason* reason);
1267 // Counts of messages sent at each priority:
1268 static int64 num_messages_[NUM_SEVERITIES]; // under log_mutex
1270 // We keep the data in a separate struct so that each instance of
1271 // LogMessage uses less stack space.
1272 LogMessageData* allocated_;
1273 LogMessageData* data_;
1275 friend class LogDestination;
1277 LogMessage(const LogMessage&);
1278 void operator=(const LogMessage&);
1281 // This class happens to be thread-hostile because all instances share
1282 // a single data buffer, but since it can only be created just before
1283 // the process dies, we don't worry so much.
1284 class GOOGLE_GLOG_DLL_DECL LogMessageFatal : public LogMessage {
1286 LogMessageFatal(const char* file, int line);
1287 LogMessageFatal(const char* file, int line, const CheckOpString& result);
1288 @ac_cv___attribute___noreturn@ ~LogMessageFatal();
1291 // A non-macro interface to the log facility; (useful
1292 // when the logging level is not a compile-time constant).
1293 inline void LogAtLevel(int const severity, std::string const &msg) {
1294 LogMessage(__FILE__, __LINE__, severity).stream() << msg;
1297 // A macro alternative of LogAtLevel. New code may want to use this
1298 // version since there are two advantages: 1. this version outputs the
1299 // file name and the line number where this macro is put like other
1300 // LOG macros, 2. this macro can be used as C++ stream.
1301 #define LOG_AT_LEVEL(severity) @ac_google_namespace@::LogMessage(__FILE__, __LINE__, severity).stream()
1303 // A small helper for CHECK_NOTNULL().
1304 template <typename T>
1305 T* CheckNotNull(const char *file, int line, const char *names, T* t) {
1307 LogMessageFatal(file, line, new std::string(names));
1312 // Allow folks to put a counter in the LOG_EVERY_X()'ed messages. This
1313 // only works if ostream is a LogStream. If the ostream is not a
1314 // LogStream you'll get an assert saying as much at runtime.
1315 GOOGLE_GLOG_DLL_DECL std::ostream& operator<<(std::ostream &os,
1316 const PRIVATE_Counter&);
1319 // Derived class for PLOG*() above.
1320 class GOOGLE_GLOG_DLL_DECL ErrnoLogMessage : public LogMessage {
1323 ErrnoLogMessage(const char* file, int line, LogSeverity severity, int ctr,
1324 void (LogMessage::*send_method)());
1326 // Postpends ": strerror(errno) [errno]".
1330 ErrnoLogMessage(const ErrnoLogMessage&);
1331 void operator=(const ErrnoLogMessage&);
1335 // This class is used to explicitly ignore values in the conditional
1336 // logging macros. This avoids compiler warnings like "value computed
1337 // is not used" and "statement has no effect".
1339 class GOOGLE_GLOG_DLL_DECL LogMessageVoidify {
1341 LogMessageVoidify() { }
1342 // This has to be an operator with a precedence lower than << but
1344 void operator&(std::ostream&) { }
1348 // Flushes all log files that contains messages that are at least of
1349 // the specified severity level. Thread-safe.
1350 GOOGLE_GLOG_DLL_DECL void FlushLogFiles(LogSeverity min_severity);
1352 // Flushes all log files that contains messages that are at least of
1353 // the specified severity level. Thread-hostile because it ignores
1354 // locking -- used for catastrophic failures.
1355 GOOGLE_GLOG_DLL_DECL void FlushLogFilesUnsafe(LogSeverity min_severity);
1358 // Set the destination to which a particular severity level of log
1359 // messages is sent. If base_filename is "", it means "don't log this
1360 // severity". Thread-safe.
1362 GOOGLE_GLOG_DLL_DECL void SetLogDestination(LogSeverity severity,
1363 const char* base_filename);
1366 // Set the basename of the symlink to the latest log file at a given
1367 // severity. If symlink_basename is empty, do not make a symlink. If
1368 // you don't call this function, the symlink basename is the
1369 // invocation name of the program. Thread-safe.
1371 GOOGLE_GLOG_DLL_DECL void SetLogSymlink(LogSeverity severity,
1372 const char* symlink_basename);
1375 // Used to send logs to some other kind of destination
1376 // Users should subclass LogSink and override send to do whatever they want.
1377 // Implementations must be thread-safe because a shared instance will
1378 // be called from whichever thread ran the LOG(XXX) line.
1379 class GOOGLE_GLOG_DLL_DECL LogSink {
1383 // Sink's logging logic (message_len is such as to exclude '\n' at the end).
1384 // This method can't use LOG() or CHECK() as logging system mutex(s) are held
1385 // during this call.
1386 virtual void send(LogSeverity severity, const char* full_filename,
1387 const char* base_filename, int line,
1388 const struct ::tm* tm_time,
1389 const char* message, size_t message_len) = 0;
1391 // Redefine this to implement waiting for
1392 // the sink's logging logic to complete.
1393 // It will be called after each send() returns,
1394 // but before that LogMessage exits or crashes.
1395 // By default this function does nothing.
1396 // Using this function one can implement complex logic for send()
1397 // that itself involves logging; and do all this w/o causing deadlocks and
1398 // inconsistent rearrangement of log messages.
1399 // E.g. if a LogSink has thread-specific actions, the send() method
1400 // can simply add the message to a queue and wake up another thread that
1401 // handles real logging while itself making some LOG() calls;
1402 // WaitTillSent() can be implemented to wait for that logic to complete.
1403 // See our unittest for an example.
1404 virtual void WaitTillSent();
1406 // Returns the normal text output of the log message.
1407 // Can be useful to implement send().
1408 static std::string ToString(LogSeverity severity, const char* file, int line,
1409 const struct ::tm* tm_time,
1410 const char* message, size_t message_len);
1413 // Add or remove a LogSink as a consumer of logging data. Thread-safe.
1414 GOOGLE_GLOG_DLL_DECL void AddLogSink(LogSink *destination);
1415 GOOGLE_GLOG_DLL_DECL void RemoveLogSink(LogSink *destination);
1418 // Specify an "extension" added to the filename specified via
1419 // SetLogDestination. This applies to all severity levels. It's
1420 // often used to append the port we're listening on to the logfile
1421 // name. Thread-safe.
1423 GOOGLE_GLOG_DLL_DECL void SetLogFilenameExtension(
1424 const char* filename_extension);
1427 // Make it so that all log messages of at least a particular severity
1428 // are logged to stderr (in addition to logging to the usual log
1429 // file(s)). Thread-safe.
1431 GOOGLE_GLOG_DLL_DECL void SetStderrLogging(LogSeverity min_severity);
1434 // Make it so that all log messages go only to stderr. Thread-safe.
1436 GOOGLE_GLOG_DLL_DECL void LogToStderr();
1439 // Make it so that all log messages of at least a particular severity are
1440 // logged via email to a list of addresses (in addition to logging to the
1441 // usual log file(s)). The list of addresses is just a string containing
1442 // the email addresses to send to (separated by spaces, say). Thread-safe.
1444 GOOGLE_GLOG_DLL_DECL void SetEmailLogging(LogSeverity min_severity,
1445 const char* addresses);
1447 // A simple function that sends email. dest is a commma-separated
1448 // list of addressess. Thread-safe.
1449 GOOGLE_GLOG_DLL_DECL bool SendEmail(const char *dest,
1450 const char *subject, const char *body);
1452 GOOGLE_GLOG_DLL_DECL const std::vector<std::string>& GetLoggingDirectories();
1454 // For tests only: Clear the internal [cached] list of logging directories to
1455 // force a refresh the next time GetLoggingDirectories is called.
1457 void TestOnly_ClearLoggingDirectoriesList();
1459 // Returns a set of existing temporary directories, which will be a
1460 // subset of the directories returned by GetLogginDirectories().
1462 GOOGLE_GLOG_DLL_DECL void GetExistingTempDirectories(
1463 std::vector<std::string>* list);
1465 // Print any fatal message again -- useful to call from signal handler
1466 // so that the last thing in the output is the fatal message.
1467 // Thread-hostile, but a race is unlikely.
1468 GOOGLE_GLOG_DLL_DECL void ReprintFatalMessage();
1470 // Truncate a log file that may be the append-only output of multiple
1471 // processes and hence can't simply be renamed/reopened (typically a
1472 // stdout/stderr). If the file "path" is > "limit" bytes, copy the
1473 // last "keep" bytes to offset 0 and truncate the rest. Since we could
1474 // be racing with other writers, this approach has the potential to
1475 // lose very small amounts of data. For security, only follow symlinks
1476 // if the path is /proc/self/fd/*
1477 GOOGLE_GLOG_DLL_DECL void TruncateLogFile(const char *path,
1478 int64 limit, int64 keep);
1480 // Truncate stdout and stderr if they are over the value specified by
1481 // --max_log_size; keep the final 1MB. This function has the same
1482 // race condition as TruncateLogFile.
1483 GOOGLE_GLOG_DLL_DECL void TruncateStdoutStderr();
1485 // Return the string representation of the provided LogSeverity level.
1487 GOOGLE_GLOG_DLL_DECL const char* GetLogSeverityName(LogSeverity severity);
1489 // ---------------------------------------------------------------------
1490 // Implementation details that are not useful to most clients
1491 // ---------------------------------------------------------------------
1493 // A Logger is the interface used by logging modules to emit entries
1494 // to a log. A typical implementation will dump formatted data to a
1495 // sequence of files. We also provide interfaces that will forward
1496 // the data to another thread so that the invoker never blocks.
1497 // Implementations should be thread-safe since the logging system
1498 // will write to them from multiple threads.
1502 class GOOGLE_GLOG_DLL_DECL Logger {
1506 // Writes "message[0,message_len-1]" corresponding to an event that
1507 // occurred at "timestamp". If "force_flush" is true, the log file
1508 // is flushed immediately.
1510 // The input message has already been formatted as deemed
1511 // appropriate by the higher level logging facility. For example,
1512 // textual log messages already contain timestamps, and the
1513 // file:linenumber header.
1514 virtual void Write(bool force_flush,
1516 const char* message,
1517 int message_len) = 0;
1519 // Flush any buffered messages
1520 virtual void Flush() = 0;
1522 // Get the current LOG file size.
1523 // The returned value is approximate since some
1524 // logged data may not have been flushed to disk yet.
1525 virtual uint32 LogSize() = 0;
1528 // Get the logger for the specified severity level. The logger
1529 // remains the property of the logging module and should not be
1530 // deleted by the caller. Thread-safe.
1531 extern GOOGLE_GLOG_DLL_DECL Logger* GetLogger(LogSeverity level);
1533 // Set the logger for the specified severity level. The logger
1534 // becomes the property of the logging module and should not
1535 // be deleted by the caller. Thread-safe.
1536 extern GOOGLE_GLOG_DLL_DECL void SetLogger(LogSeverity level, Logger* logger);
1540 // glibc has traditionally implemented two incompatible versions of
1541 // strerror_r(). There is a poorly defined convention for picking the
1542 // version that we want, but it is not clear whether it even works with
1543 // all versions of glibc.
1544 // So, instead, we provide this wrapper that automatically detects the
1545 // version that is in use, and then implements POSIX semantics.
1546 // N.B. In addition to what POSIX says, we also guarantee that "buf" will
1547 // be set to an empty string, if this function failed. This means, in most
1548 // cases, you do not need to check the error code and you can directly
1549 // use the value of "buf". It will never have an undefined value.
1550 // DEPRECATED: Use StrError(int) instead.
1551 GOOGLE_GLOG_DLL_DECL int posix_strerror_r(int err, char *buf, size_t len);
1553 // A thread-safe replacement for strerror(). Returns a string describing the
1554 // given POSIX error code.
1555 GOOGLE_GLOG_DLL_DECL std::string StrError(int err);
1557 // A class for which we define operator<<, which does nothing.
1558 class GOOGLE_GLOG_DLL_DECL NullStream : public LogMessage::LogStream {
1560 // Initialize the LogStream so the messages can be written somewhere
1561 // (they'll never be actually displayed). This will be needed if a
1562 // NullStream& is implicitly converted to LogStream&, in which case
1563 // the overloaded NullStream::operator<< will not be invoked.
1564 NullStream() : LogMessage::LogStream(message_buffer_, 1, 0) { }
1565 NullStream(const char* /*file*/, int /*line*/,
1566 const CheckOpString& /*result*/) :
1567 LogMessage::LogStream(message_buffer_, 1, 0) { }
1568 NullStream &stream() { return *this; }
1570 // A very short buffer for messages (which we discard anyway). This
1571 // will be needed if NullStream& converted to LogStream& (e.g. as a
1572 // result of a conditional expression).
1573 char message_buffer_[2];
1576 // Do nothing. This operator is inline, allowing the message to be
1577 // compiled away. The message will not be compiled away if we do
1578 // something like (flag ? LOG(INFO) : LOG(ERROR)) << message; when
1579 // SKIP_LOG=WARNING. In those cases, NullStream will be implicitly
1580 // converted to LogStream and the message will be computed and then
1581 // quietly discarded.
1583 inline NullStream& operator<<(NullStream &str, const T &) { return str; }
1585 // Similar to NullStream, but aborts the program (without stack
1586 // trace), like LogMessageFatal.
1587 class GOOGLE_GLOG_DLL_DECL NullStreamFatal : public NullStream {
1589 NullStreamFatal() { }
1590 NullStreamFatal(const char* file, int line, const CheckOpString& result) :
1591 NullStream(file, line, result) { }
1592 @ac_cv___attribute___noreturn@ ~NullStreamFatal() throw () { _exit(1); }
1595 // Install a signal handler that will dump signal information and a stack
1596 // trace when the program crashes on certain signals. We'll install the
1597 // signal handler for the following signals.
1599 // SIGSEGV, SIGILL, SIGFPE, SIGABRT, SIGBUS, and SIGTERM.
1601 // By default, the signal handler will write the failure dump to the
1602 // standard error. You can customize the destination by installing your
1603 // own writer function by InstallFailureWriter() below.
1605 // Note on threading:
1607 // The function should be called before threads are created, if you want
1608 // to use the failure signal handler for all threads. The stack trace
1609 // will be shown only for the thread that receives the signal. In other
1610 // words, stack traces of other threads won't be shown.
1611 GOOGLE_GLOG_DLL_DECL void InstallFailureSignalHandler();
1613 // Installs a function that is used for writing the failure dump. "data"
1614 // is the pointer to the beginning of a message to be written, and "size"
1615 // is the size of the message. You should not expect the data is
1616 // terminated with '\0'.
1617 GOOGLE_GLOG_DLL_DECL void InstallFailureWriter(
1618 void (*writer)(const char* data, int size));
1620 @ac_google_end_namespace@
1622 #endif // _LOGGING_H_