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@
51 // Annoying stuff for windows -- makes sure clients can import these functions
52 #ifndef GOOGLE_GLOG_DLL_DECL
53 # if defined(_WIN32) && !defined(__CYGWIN__)
54 # define GOOGLE_GLOG_DLL_DECL __declspec(dllimport)
56 # define GOOGLE_GLOG_DLL_DECL
60 #define GLOG_MSVC_PUSH_DISABLE_WARNING(n) __pragma(warning(push)) \
61 __pragma(warning(disable:n))
62 #define GLOG_MSVC_POP_WARNING() __pragma(warning(pop))
64 #define GLOG_MSVC_PUSH_DISABLE_WARNING(n)
65 #define GLOG_MSVC_POP_WARNING()
68 // We care a lot about number of bits things take up. Unfortunately,
69 // systems define their bit-specific ints in a lot of different ways.
70 // We use our own way, and have a typedef to get there.
71 // Note: these commands below may look like "#if 1" or "#if 0", but
72 // that's because they were constructed that way at ./configure time.
73 // Look at logging.h.in to see how they're calculated (based on your config).
74 #if @ac_cv_have_stdint_h@
75 #include <stdint.h> // the normal place uint16_t is defined
77 #if @ac_cv_have_systypes_h@
78 #include <sys/types.h> // the normal place u_int16_t is defined
80 #if @ac_cv_have_inttypes_h@
81 #include <inttypes.h> // a third place for uint16_t or u_int16_t
84 #if @ac_cv_have_libgflags@
85 #include <gflags/gflags.h>
88 @ac_google_start_namespace@
90 #if @ac_cv_have_uint16_t@ // the C99 format
91 typedef int32_t int32;
92 typedef uint32_t uint32;
93 typedef int64_t int64;
94 typedef uint64_t uint64;
95 #elif @ac_cv_have_u_int16_t@ // the BSD format
96 typedef int32_t int32;
97 typedef u_int32_t uint32;
98 typedef int64_t int64;
99 typedef u_int64_t uint64;
100 #elif @ac_cv_have___uint16@ // the windows (vc7) format
101 typedef __int32 int32;
102 typedef unsigned __int32 uint32;
103 typedef __int64 int64;
104 typedef unsigned __int64 uint64;
106 #error Do not know how to define a 32-bit integer quantity on your system
109 @ac_google_end_namespace@
111 // The global value of GOOGLE_STRIP_LOG. All the messages logged to
112 // LOG(XXX) with severity less than GOOGLE_STRIP_LOG will not be displayed.
113 // If it can be determined at compile time that the message will not be
114 // printed, the statement will be compiled out.
116 // Example: to strip out all INFO and WARNING messages, use the value
117 // of 2 below. To make an exception for WARNING messages from a single
118 // file, add "#define GOOGLE_STRIP_LOG 1" to that file _before_ including
120 #ifndef GOOGLE_STRIP_LOG
121 #define GOOGLE_STRIP_LOG 0
124 // GCC can be told that a certain branch is not likely to be taken (for
125 // instance, a CHECK failure), and use that information in static analysis.
126 // Giving it this information can help it optimize for the common case in
127 // the absence of better information (ie. -fprofile-arcs).
129 #ifndef GOOGLE_PREDICT_BRANCH_NOT_TAKEN
130 #if @ac_cv_have___builtin_expect@
131 #define GOOGLE_PREDICT_BRANCH_NOT_TAKEN(x) (__builtin_expect(x, 0))
133 #define GOOGLE_PREDICT_BRANCH_NOT_TAKEN(x) x
137 #ifndef GOOGLE_PREDICT_FALSE
138 #if @ac_cv_have___builtin_expect@
139 #define GOOGLE_PREDICT_FALSE(x) (__builtin_expect(x, 0))
141 #define GOOGLE_PREDICT_FALSE(x) x
145 #ifndef GOOGLE_PREDICT_TRUE
146 #if @ac_cv_have___builtin_expect@
147 #define GOOGLE_PREDICT_TRUE(x) (__builtin_expect(!!(x), 1))
149 #define GOOGLE_PREDICT_TRUE(x) x
154 // Make a bunch of macros for logging. The way to log things is to stream
155 // things to LOG(<a particular severity level>). E.g.,
157 // LOG(INFO) << "Found " << num_cookies << " cookies";
159 // You can capture log messages in a string, rather than reporting them
162 // vector<string> errors;
163 // LOG_STRING(ERROR, &errors) << "Couldn't parse cookie #" << cookie_num;
165 // This pushes back the new error onto 'errors'; if given a NULL pointer,
166 // it reports the error via LOG(ERROR).
168 // You can also do conditional logging:
170 // LOG_IF(INFO, num_cookies > 10) << "Got lots of cookies";
172 // You can also do occasional logging (log every n'th occurrence of an
175 // LOG_EVERY_N(INFO, 10) << "Got the " << google::COUNTER << "th cookie";
177 // The above will cause log messages to be output on the 1st, 11th, 21st, ...
178 // times it is executed. Note that the special google::COUNTER value is used
179 // to identify which repetition is happening.
181 // You can also do occasional conditional logging (log every n'th
182 // occurrence of an event, when condition is satisfied):
184 // LOG_IF_EVERY_N(INFO, (size > 1024), 10) << "Got the " << google::COUNTER
185 // << "th big cookie";
187 // You can log messages the first N times your code executes a line. E.g.
189 // LOG_FIRST_N(INFO, 20) << "Got the " << google::COUNTER << "th cookie";
191 // Outputs log messages for the first 20 times it is executed.
193 // Analogous SYSLOG, SYSLOG_IF, and SYSLOG_EVERY_N macros are available.
194 // These log to syslog as well as to the normal logs. If you use these at
195 // all, you need to be aware that syslog can drastically reduce performance,
196 // especially if it is configured for remote logging! Don't use these
197 // unless you fully understand this and have a concrete need to use them.
198 // Even then, try to minimize your use of them.
200 // There are also "debug mode" logging macros like the ones above:
202 // DLOG(INFO) << "Found cookies";
204 // DLOG_IF(INFO, num_cookies > 10) << "Got lots of cookies";
206 // DLOG_EVERY_N(INFO, 10) << "Got the " << google::COUNTER << "th cookie";
208 // All "debug mode" logging is compiled away to nothing for non-debug mode
213 // LOG_ASSERT(assertion);
214 // DLOG_ASSERT(assertion);
216 // which is syntactic sugar for {,D}LOG_IF(FATAL, assert fails) << assertion;
218 // There are "verbose level" logging macros. They look like
220 // VLOG(1) << "I'm printed when you run the program with --v=1 or more";
221 // VLOG(2) << "I'm printed when you run the program with --v=2 or more";
223 // These always log at the INFO log level (when they log at all).
224 // The verbose logging can also be turned on module-by-module. For instance,
225 // --vmodule=mapreduce=2,file=1,gfs*=3 --v=0
227 // a. VLOG(2) and lower messages to be printed from mapreduce.{h,cc}
228 // b. VLOG(1) and lower messages to be printed from file.{h,cc}
229 // c. VLOG(3) and lower messages to be printed from files prefixed with "gfs"
230 // d. VLOG(0) and lower messages to be printed from elsewhere
232 // The wildcarding functionality shown by (c) supports both '*' (match
233 // 0 or more characters) and '?' (match any single character) wildcards.
235 // There's also VLOG_IS_ON(n) "verbose level" condition macro. To be used as
237 // if (VLOG_IS_ON(2)) {
238 // // do some logging preparation and logging
239 // // that can't be accomplished with just VLOG(2) << ...;
242 // There are also VLOG_IF, VLOG_EVERY_N and VLOG_IF_EVERY_N "verbose level"
243 // condition macros for sample cases, when some extra computation and
244 // preparation for logs is not needed.
245 // VLOG_IF(1, (size > 1024))
246 // << "I'm printed when size is more than 1024 and when you run the "
247 // "program with --v=1 or more";
248 // VLOG_EVERY_N(1, 10)
249 // << "I'm printed every 10th occurrence, and when you run the program "
250 // "with --v=1 or more. Present occurence is " << google::COUNTER;
251 // VLOG_IF_EVERY_N(1, (size > 1024), 10)
252 // << "I'm printed on every 10th occurence of case when size is more "
253 // " than 1024, when you run the program with --v=1 or more. ";
254 // "Present occurence is " << google::COUNTER;
256 // The supported severity levels for macros that allow you to specify one
257 // are (in increasing order of severity) INFO, WARNING, ERROR, and FATAL.
258 // Note that messages of a given severity are logged not only in the
259 // logfile for that severity, but also in all logfiles of lower severity.
260 // E.g., a message of severity FATAL will be logged to the logfiles of
261 // severity FATAL, ERROR, WARNING, and INFO.
263 // There is also the special severity of DFATAL, which logs FATAL in
264 // debug mode, ERROR in normal mode.
266 // Very important: logging a message at the FATAL severity level causes
267 // the program to terminate (after the message is logged).
269 // Unless otherwise specified, logs will be written to the filename
270 // "<program name>.<hostname>.<user name>.log.<severity level>.", followed
271 // by the date, time, and pid (you can't prevent the date, time, and pid
272 // from being in the filename).
274 // The logging code takes two flags:
275 // --v=# set the verbose level
276 // --logtostderr log all the messages to stderr instead of to logfiles
278 // LOG LINE PREFIX FORMAT
280 // Log lines have this form:
282 // Lmmdd hh:mm:ss.uuuuuu threadid file:line] msg...
284 // where the fields are defined as follows:
286 // L A single character, representing the log level
288 // mm The month (zero padded; ie May is '05')
289 // dd The day (zero padded)
290 // hh:mm:ss.uuuuuu Time in hours, minutes and fractional seconds
291 // threadid The space-padded thread ID as returned by GetTID()
292 // (this matches the PID on Linux)
293 // file The file name
294 // line The line number
295 // msg The user-supplied message
299 // I1103 11:57:31.739339 24395 google.cc:2341] Command line: ./some_prog
300 // I1103 11:57:31.739403 24395 google.cc:2342] Process id 24395
302 // NOTE: although the microseconds are useful for comparing events on
303 // a single machine, clocks on different machines may not be well
304 // synchronized. Hence, use caution when comparing the low bits of
305 // timestamps from different machines.
307 #ifndef DECLARE_VARIABLE
308 #define MUST_UNDEF_GFLAGS_DECLARE_MACROS
309 #define DECLARE_VARIABLE(type, shorttype, name, tn) \
310 namespace fL##shorttype { \
311 extern GOOGLE_GLOG_DLL_DECL type FLAGS_##name; \
313 using fL##shorttype::FLAGS_##name
315 // bool specialization
316 #define DECLARE_bool(name) \
317 DECLARE_VARIABLE(bool, B, name, bool)
319 // int32 specialization
320 #define DECLARE_int32(name) \
321 DECLARE_VARIABLE(@ac_google_namespace@::int32, I, name, int32)
323 // Special case for string, because we have to specify the namespace
324 // std::string, which doesn't play nicely with our FLAG__namespace hackery.
325 #define DECLARE_string(name) \
327 extern GOOGLE_GLOG_DLL_DECL std::string& FLAGS_##name; \
329 using fLS::FLAGS_##name
332 // Set whether log messages go to stderr instead of logfiles
333 DECLARE_bool(logtostderr);
335 // Set whether log messages go to stderr in addition to logfiles.
336 DECLARE_bool(alsologtostderr);
338 // Set color messages logged to stderr (if supported by terminal).
339 DECLARE_bool(colorlogtostderr);
341 // Log messages at a level >= this flag are automatically sent to
342 // stderr in addition to log files.
343 DECLARE_int32(stderrthreshold);
345 // Set whether the log prefix should be prepended to each line of output.
346 DECLARE_bool(log_prefix);
348 // Log messages at a level <= this flag are buffered.
349 // Log messages at a higher level are flushed immediately.
350 DECLARE_int32(logbuflevel);
352 // Sets the maximum number of seconds which logs may be buffered for.
353 DECLARE_int32(logbufsecs);
355 // Log suppression level: messages logged at a lower level than this
357 DECLARE_int32(minloglevel);
359 // If specified, logfiles are written into this directory instead of the
360 // default logging directory.
361 DECLARE_string(log_dir);
363 // Set the log file mode.
364 DECLARE_int32(logfile_mode);
366 // Sets the path of the directory into which to put additional links
368 DECLARE_string(log_link);
370 DECLARE_int32(v); // in vlog_is_on.cc
372 // Sets the maximum log file size (in MB).
373 DECLARE_int32(max_log_size);
375 // Sets whether to avoid logging to the disk if the disk is full.
376 DECLARE_bool(stop_logging_if_full_disk);
378 #ifdef MUST_UNDEF_GFLAGS_DECLARE_MACROS
379 #undef MUST_UNDEF_GFLAGS_DECLARE_MACROS
380 #undef DECLARE_VARIABLE
383 #undef DECLARE_string
386 // Log messages below the GOOGLE_STRIP_LOG level will be compiled away for
387 // security reasons. See LOG(severtiy) below.
389 // A few definitions of macros that don't generate much code. Since
390 // LOG(INFO) and its ilk are used all over our code, it's
391 // better to have compact code for these operations.
393 #if GOOGLE_STRIP_LOG == 0
394 #define COMPACT_GOOGLE_LOG_INFO @ac_google_namespace@::LogMessage( \
396 #define LOG_TO_STRING_INFO(message) @ac_google_namespace@::LogMessage( \
397 __FILE__, __LINE__, @ac_google_namespace@::GLOG_INFO, message)
399 #define COMPACT_GOOGLE_LOG_INFO @ac_google_namespace@::NullStream()
400 #define LOG_TO_STRING_INFO(message) @ac_google_namespace@::NullStream()
403 #if GOOGLE_STRIP_LOG <= 1
404 #define COMPACT_GOOGLE_LOG_WARNING @ac_google_namespace@::LogMessage( \
405 __FILE__, __LINE__, @ac_google_namespace@::GLOG_WARNING)
406 #define LOG_TO_STRING_WARNING(message) @ac_google_namespace@::LogMessage( \
407 __FILE__, __LINE__, @ac_google_namespace@::GLOG_WARNING, message)
409 #define COMPACT_GOOGLE_LOG_WARNING @ac_google_namespace@::NullStream()
410 #define LOG_TO_STRING_WARNING(message) @ac_google_namespace@::NullStream()
413 #if GOOGLE_STRIP_LOG <= 2
414 #define COMPACT_GOOGLE_LOG_ERROR @ac_google_namespace@::LogMessage( \
415 __FILE__, __LINE__, @ac_google_namespace@::GLOG_ERROR)
416 #define LOG_TO_STRING_ERROR(message) @ac_google_namespace@::LogMessage( \
417 __FILE__, __LINE__, @ac_google_namespace@::GLOG_ERROR, message)
419 #define COMPACT_GOOGLE_LOG_ERROR @ac_google_namespace@::NullStream()
420 #define LOG_TO_STRING_ERROR(message) @ac_google_namespace@::NullStream()
423 #if GOOGLE_STRIP_LOG <= 3
424 #define COMPACT_GOOGLE_LOG_FATAL @ac_google_namespace@::LogMessageFatal( \
426 #define LOG_TO_STRING_FATAL(message) @ac_google_namespace@::LogMessage( \
427 __FILE__, __LINE__, @ac_google_namespace@::GLOG_FATAL, message)
429 #define COMPACT_GOOGLE_LOG_FATAL @ac_google_namespace@::NullStreamFatal()
430 #define LOG_TO_STRING_FATAL(message) @ac_google_namespace@::NullStreamFatal()
433 // For DFATAL, we want to use LogMessage (as opposed to
434 // LogMessageFatal), to be consistent with the original behavior.
436 #define COMPACT_GOOGLE_LOG_DFATAL COMPACT_GOOGLE_LOG_ERROR
437 #elif GOOGLE_STRIP_LOG <= 3
438 #define COMPACT_GOOGLE_LOG_DFATAL @ac_google_namespace@::LogMessage( \
439 __FILE__, __LINE__, @ac_google_namespace@::GLOG_FATAL)
441 #define COMPACT_GOOGLE_LOG_DFATAL @ac_google_namespace@::NullStreamFatal()
444 #define GOOGLE_LOG_INFO(counter) @ac_google_namespace@::LogMessage(__FILE__, __LINE__, @ac_google_namespace@::GLOG_INFO, counter, &@ac_google_namespace@::LogMessage::SendToLog)
445 #define SYSLOG_INFO(counter) \
446 @ac_google_namespace@::LogMessage(__FILE__, __LINE__, @ac_google_namespace@::GLOG_INFO, counter, \
447 &@ac_google_namespace@::LogMessage::SendToSyslogAndLog)
448 #define GOOGLE_LOG_WARNING(counter) \
449 @ac_google_namespace@::LogMessage(__FILE__, __LINE__, @ac_google_namespace@::GLOG_WARNING, counter, \
450 &@ac_google_namespace@::LogMessage::SendToLog)
451 #define SYSLOG_WARNING(counter) \
452 @ac_google_namespace@::LogMessage(__FILE__, __LINE__, @ac_google_namespace@::GLOG_WARNING, counter, \
453 &@ac_google_namespace@::LogMessage::SendToSyslogAndLog)
454 #define GOOGLE_LOG_ERROR(counter) \
455 @ac_google_namespace@::LogMessage(__FILE__, __LINE__, @ac_google_namespace@::GLOG_ERROR, counter, \
456 &@ac_google_namespace@::LogMessage::SendToLog)
457 #define SYSLOG_ERROR(counter) \
458 @ac_google_namespace@::LogMessage(__FILE__, __LINE__, @ac_google_namespace@::GLOG_ERROR, counter, \
459 &@ac_google_namespace@::LogMessage::SendToSyslogAndLog)
460 #define GOOGLE_LOG_FATAL(counter) \
461 @ac_google_namespace@::LogMessage(__FILE__, __LINE__, @ac_google_namespace@::GLOG_FATAL, counter, \
462 &@ac_google_namespace@::LogMessage::SendToLog)
463 #define SYSLOG_FATAL(counter) \
464 @ac_google_namespace@::LogMessage(__FILE__, __LINE__, @ac_google_namespace@::GLOG_FATAL, counter, \
465 &@ac_google_namespace@::LogMessage::SendToSyslogAndLog)
466 #define GOOGLE_LOG_DFATAL(counter) \
467 @ac_google_namespace@::LogMessage(__FILE__, __LINE__, @ac_google_namespace@::DFATAL_LEVEL, counter, \
468 &@ac_google_namespace@::LogMessage::SendToLog)
469 #define SYSLOG_DFATAL(counter) \
470 @ac_google_namespace@::LogMessage(__FILE__, __LINE__, @ac_google_namespace@::DFATAL_LEVEL, counter, \
471 &@ac_google_namespace@::LogMessage::SendToSyslogAndLog)
473 #if defined(WIN32) || defined(_WIN32) || defined(__WIN32__) || defined(__CYGWIN__) || defined(__CYGWIN32__)
474 // A very useful logging macro to log windows errors:
475 #define LOG_SYSRESULT(result) \
476 if (FAILED(HRESULT_FROM_WIN32(result))) { \
477 LPSTR message = NULL; \
478 LPSTR msg = reinterpret_cast<LPSTR>(&message); \
479 DWORD message_length = FormatMessageA(FORMAT_MESSAGE_ALLOCATE_BUFFER | \
480 FORMAT_MESSAGE_FROM_SYSTEM, \
481 0, result, 0, msg, 100, NULL); \
482 if (message_length > 0) { \
483 @ac_google_namespace@::LogMessage(__FILE__, __LINE__, @ac_google_namespace@::GLOG_ERROR, 0, \
484 &@ac_google_namespace@::LogMessage::SendToLog).stream() \
485 << reinterpret_cast<const char*>(message); \
486 LocalFree(message); \
491 // We use the preprocessor's merging operator, "##", so that, e.g.,
492 // LOG(INFO) becomes the token GOOGLE_LOG_INFO. There's some funny
493 // subtle difference between ostream member streaming functions (e.g.,
494 // ostream::operator<<(int) and ostream non-member streaming functions
495 // (e.g., ::operator<<(ostream&, string&): it turns out that it's
496 // impossible to stream something like a string directly to an unnamed
497 // ostream. We employ a neat hack by calling the stream() member
498 // function of LogMessage which seems to avoid the problem.
499 #define LOG(severity) COMPACT_GOOGLE_LOG_ ## severity.stream()
500 #define SYSLOG(severity) SYSLOG_ ## severity(0).stream()
502 @ac_google_start_namespace@
504 // They need the definitions of integer types.
505 #include "glog/log_severity.h"
506 #include "glog/vlog_is_on.h"
508 // Initialize google's logging library. You will see the program name
509 // specified by argv0 in log outputs.
510 GOOGLE_GLOG_DLL_DECL void InitGoogleLogging(const char* argv0);
512 // Shutdown google's logging library.
513 GOOGLE_GLOG_DLL_DECL void ShutdownGoogleLogging();
515 // Install a function which will be called after LOG(FATAL).
516 GOOGLE_GLOG_DLL_DECL void InstallFailureFunction(void (*fail_func)());
518 class LogSink; // defined below
520 // If a non-NULL sink pointer is given, we push this message to that sink.
521 // For LOG_TO_SINK we then do normal LOG(severity) logging as well.
522 // This is useful for capturing messages and passing/storing them
523 // somewhere more specific than the global log of the process.
526 // LogSeverity severity;
527 // The cast is to disambiguate NULL arguments.
528 #define LOG_TO_SINK(sink, severity) \
529 @ac_google_namespace@::LogMessage( \
530 __FILE__, __LINE__, \
531 @ac_google_namespace@::GLOG_ ## severity, \
532 static_cast<@ac_google_namespace@::LogSink*>(sink), true).stream()
533 #define LOG_TO_SINK_BUT_NOT_TO_LOGFILE(sink, severity) \
534 @ac_google_namespace@::LogMessage( \
535 __FILE__, __LINE__, \
536 @ac_google_namespace@::GLOG_ ## severity, \
537 static_cast<@ac_google_namespace@::LogSink*>(sink), false).stream()
539 // If a non-NULL string pointer is given, we write this message to that string.
540 // We then do normal LOG(severity) logging as well.
541 // This is useful for capturing messages and storing them somewhere more
542 // specific than the global log of the process.
545 // LogSeverity severity;
546 // The cast is to disambiguate NULL arguments.
547 // NOTE: LOG(severity) expands to LogMessage().stream() for the specified
549 #define LOG_TO_STRING(severity, message) \
550 LOG_TO_STRING_##severity(static_cast<string*>(message)).stream()
552 // If a non-NULL pointer is given, we push the message onto the end
553 // of a vector of strings; otherwise, we report it with LOG(severity).
554 // This is handy for capturing messages and perhaps passing them back
555 // to the caller, rather than reporting them immediately.
557 // LogSeverity severity;
558 // vector<string> *outvec;
559 // The cast is to disambiguate NULL arguments.
560 #define LOG_STRING(severity, outvec) \
561 LOG_TO_STRING_##severity(static_cast<std::vector<std::string>*>(outvec)).stream()
563 #define LOG_IF(severity, condition) \
564 !(condition) ? (void) 0 : @ac_google_namespace@::LogMessageVoidify() & LOG(severity)
565 #define SYSLOG_IF(severity, condition) \
566 !(condition) ? (void) 0 : @ac_google_namespace@::LogMessageVoidify() & SYSLOG(severity)
568 #define LOG_ASSERT(condition) \
569 LOG_IF(FATAL, !(condition)) << "Assert failed: " #condition
570 #define SYSLOG_ASSERT(condition) \
571 SYSLOG_IF(FATAL, !(condition)) << "Assert failed: " #condition
573 // CHECK dies with a fatal error if condition is not true. It is *not*
574 // controlled by NDEBUG, so the check will be executed regardless of
575 // compilation mode. Therefore, it is safe to do things like:
576 // CHECK(fp->Write(x) == 4)
577 #define CHECK(condition) \
578 LOG_IF(FATAL, GOOGLE_PREDICT_BRANCH_NOT_TAKEN(!(condition))) \
579 << "Check failed: " #condition " "
581 // A container for a string pointer which can be evaluated to a bool -
582 // true iff the pointer is NULL.
583 struct CheckOpString {
584 CheckOpString(std::string* str) : str_(str) { }
585 // No destructor: if str_ is non-NULL, we're about to LOG(FATAL),
586 // so there's no point in cleaning up str_.
587 operator bool() const {
588 return GOOGLE_PREDICT_BRANCH_NOT_TAKEN(str_ != NULL);
593 // Function is overloaded for integral types to allow static const
594 // integrals declared in classes and not defined to be used as arguments to
595 // CHECK* macros. It's not encouraged though.
597 inline const T& GetReferenceableValue(const T& t) { return t; }
598 inline char GetReferenceableValue(char t) { return t; }
599 inline unsigned char GetReferenceableValue(unsigned char t) { return t; }
600 inline signed char GetReferenceableValue(signed char t) { return t; }
601 inline short GetReferenceableValue(short t) { return t; }
602 inline unsigned short GetReferenceableValue(unsigned short t) { return t; }
603 inline int GetReferenceableValue(int t) { return t; }
604 inline unsigned int GetReferenceableValue(unsigned int t) { return t; }
605 inline long GetReferenceableValue(long t) { return t; }
606 inline unsigned long GetReferenceableValue(unsigned long t) { return t; }
607 inline long long GetReferenceableValue(long long t) { return t; }
608 inline unsigned long long GetReferenceableValue(unsigned long long t) {
612 // This is a dummy class to define the following operator.
613 struct DummyClassToDefineOperator {};
615 @ac_google_end_namespace@
617 // Define global operator<< to declare using ::operator<<.
618 // This declaration will allow use to use CHECK macros for user
619 // defined classes which have operator<< (e.g., stl_logging.h).
620 inline std::ostream& operator<<(
621 std::ostream& out, const google::DummyClassToDefineOperator&) {
625 @ac_google_start_namespace@
627 // This formats a value for a failing CHECK_XX statement. Ordinarily,
628 // it uses the definition for operator<<, with a few special cases below.
629 template <typename T>
630 inline void MakeCheckOpValueString(std::ostream* os, const T& v) {
634 // Overrides for char types provide readable values for unprintable
636 template <> GOOGLE_GLOG_DLL_DECL
637 void MakeCheckOpValueString(std::ostream* os, const char& v);
638 template <> GOOGLE_GLOG_DLL_DECL
639 void MakeCheckOpValueString(std::ostream* os, const signed char& v);
640 template <> GOOGLE_GLOG_DLL_DECL
641 void MakeCheckOpValueString(std::ostream* os, const unsigned char& v);
643 // Build the error message string. Specify no inlining for code size.
644 template <typename T1, typename T2>
645 std::string* MakeCheckOpString(const T1& v1, const T2& v2, const char* exprtext)
646 @ac_cv___attribute___noinline@;
651 // If "s" is less than base_logging::INFO, returns base_logging::INFO.
652 // If "s" is greater than base_logging::FATAL, returns
653 // base_logging::ERROR. Otherwise, returns "s".
654 LogSeverity NormalizeSeverity(LogSeverity s);
656 } // namespace internal
658 // A helper class for formatting "expr (V1 vs. V2)" in a CHECK_XX
659 // statement. See MakeCheckOpString for sample usage. Other
660 // approaches were considered: use of a template method (e.g.,
661 // base::BuildCheckOpString(exprtext, base::Print<T1>, &v1,
662 // base::Print<T2>, &v2), however this approach has complications
663 // related to volatile arguments and function-pointer arguments).
664 class GOOGLE_GLOG_DLL_DECL CheckOpMessageBuilder {
666 // Inserts "exprtext" and " (" to the stream.
667 explicit CheckOpMessageBuilder(const char *exprtext);
668 // Deletes "stream_".
669 ~CheckOpMessageBuilder();
670 // For inserting the first variable.
671 std::ostream* ForVar1() { return stream_; }
672 // For inserting the second variable (adds an intermediate " vs. ").
673 std::ostream* ForVar2();
674 // Get the result (inserts the closing ")").
675 std::string* NewString();
678 std::ostringstream *stream_;
683 template <typename T1, typename T2>
684 std::string* MakeCheckOpString(const T1& v1, const T2& v2, const char* exprtext) {
685 base::CheckOpMessageBuilder comb(exprtext);
686 MakeCheckOpValueString(comb.ForVar1(), v1);
687 MakeCheckOpValueString(comb.ForVar2(), v2);
688 return comb.NewString();
691 // Helper functions for CHECK_OP macro.
692 // The (int, int) specialization works around the issue that the compiler
693 // will not instantiate the template version of the function on values of
694 // unnamed enum type - see comment below.
695 #define DEFINE_CHECK_OP_IMPL(name, op) \
696 template <typename T1, typename T2> \
697 inline std::string* name##Impl(const T1& v1, const T2& v2, \
698 const char* exprtext) { \
699 if (GOOGLE_PREDICT_TRUE(v1 op v2)) return NULL; \
700 else return MakeCheckOpString(v1, v2, exprtext); \
702 inline std::string* name##Impl(int v1, int v2, const char* exprtext) { \
703 return name##Impl<int, int>(v1, v2, exprtext); \
706 // We use the full name Check_EQ, Check_NE, etc. in case the file including
707 // base/logging.h provides its own #defines for the simpler names EQ, NE, etc.
708 // This happens if, for example, those are used as token names in a
710 DEFINE_CHECK_OP_IMPL(Check_EQ, ==) // Compilation error with CHECK_EQ(NULL, x)?
711 DEFINE_CHECK_OP_IMPL(Check_NE, !=) // Use CHECK(x == NULL) instead.
712 DEFINE_CHECK_OP_IMPL(Check_LE, <=)
713 DEFINE_CHECK_OP_IMPL(Check_LT, < )
714 DEFINE_CHECK_OP_IMPL(Check_GE, >=)
715 DEFINE_CHECK_OP_IMPL(Check_GT, > )
716 #undef DEFINE_CHECK_OP_IMPL
718 // Helper macro for binary operators.
719 // Don't use this macro directly in your code, use CHECK_EQ et al below.
721 #if defined(STATIC_ANALYSIS)
722 // Only for static analysis tool to know that it is equivalent to assert
723 #define CHECK_OP_LOG(name, op, val1, val2, log) CHECK((val1) op (val2))
724 #elif !defined(NDEBUG)
725 // In debug mode, avoid constructing CheckOpStrings if possible,
726 // to reduce the overhead of CHECK statments by 2x.
727 // Real DCHECK-heavy tests have seen 1.5x speedups.
729 // The meaning of "string" might be different between now and
730 // when this macro gets invoked (e.g., if someone is experimenting
731 // with other string implementations that get defined after this
732 // file is included). Save the current meaning now and use it
734 typedef std::string _Check_string;
735 #define CHECK_OP_LOG(name, op, val1, val2, log) \
736 while (@ac_google_namespace@::_Check_string* _result = \
737 @ac_google_namespace@::Check##name##Impl( \
738 @ac_google_namespace@::GetReferenceableValue(val1), \
739 @ac_google_namespace@::GetReferenceableValue(val2), \
740 #val1 " " #op " " #val2)) \
741 log(__FILE__, __LINE__, \
742 @ac_google_namespace@::CheckOpString(_result)).stream()
744 // In optimized mode, use CheckOpString to hint to compiler that
745 // the while condition is unlikely.
746 #define CHECK_OP_LOG(name, op, val1, val2, log) \
747 while (@ac_google_namespace@::CheckOpString _result = \
748 @ac_google_namespace@::Check##name##Impl( \
749 @ac_google_namespace@::GetReferenceableValue(val1), \
750 @ac_google_namespace@::GetReferenceableValue(val2), \
751 #val1 " " #op " " #val2)) \
752 log(__FILE__, __LINE__, _result).stream()
753 #endif // STATIC_ANALYSIS, !NDEBUG
755 #if GOOGLE_STRIP_LOG <= 3
756 #define CHECK_OP(name, op, val1, val2) \
757 CHECK_OP_LOG(name, op, val1, val2, @ac_google_namespace@::LogMessageFatal)
759 #define CHECK_OP(name, op, val1, val2) \
760 CHECK_OP_LOG(name, op, val1, val2, @ac_google_namespace@::NullStreamFatal)
761 #endif // STRIP_LOG <= 3
763 // Equality/Inequality checks - compare two values, and log a FATAL message
764 // including the two values when the result is not as expected. The values
765 // must have operator<<(ostream, ...) defined.
767 // You may append to the error message like so:
768 // CHECK_NE(1, 2) << ": The world must be ending!";
770 // We are very careful to ensure that each argument is evaluated exactly
771 // once, and that anything which is legal to pass as a function argument is
772 // legal here. In particular, the arguments may be temporary expressions
773 // which will end up being destroyed at the end of the apparent statement,
775 // CHECK_EQ(string("abc")[1], 'b');
777 // WARNING: These don't compile correctly if one of the arguments is a pointer
778 // and the other is NULL. To work around this, simply static_cast NULL to the
779 // type of the desired pointer.
781 #define CHECK_EQ(val1, val2) CHECK_OP(_EQ, ==, val1, val2)
782 #define CHECK_NE(val1, val2) CHECK_OP(_NE, !=, val1, val2)
783 #define CHECK_LE(val1, val2) CHECK_OP(_LE, <=, val1, val2)
784 #define CHECK_LT(val1, val2) CHECK_OP(_LT, < , val1, val2)
785 #define CHECK_GE(val1, val2) CHECK_OP(_GE, >=, val1, val2)
786 #define CHECK_GT(val1, val2) CHECK_OP(_GT, > , val1, val2)
788 // Check that the input is non NULL. This very useful in constructor
789 // initializer lists.
791 #define CHECK_NOTNULL(val) \
792 @ac_google_namespace@::CheckNotNull(__FILE__, __LINE__, "'" #val "' Must be non NULL", (val))
794 // Helper functions for string comparisons.
795 // To avoid bloat, the definitions are in logging.cc.
796 #define DECLARE_CHECK_STROP_IMPL(func, expected) \
797 GOOGLE_GLOG_DLL_DECL std::string* Check##func##expected##Impl( \
798 const char* s1, const char* s2, const char* names);
799 DECLARE_CHECK_STROP_IMPL(strcmp, true)
800 DECLARE_CHECK_STROP_IMPL(strcmp, false)
801 DECLARE_CHECK_STROP_IMPL(strcasecmp, true)
802 DECLARE_CHECK_STROP_IMPL(strcasecmp, false)
803 #undef DECLARE_CHECK_STROP_IMPL
805 // Helper macro for string comparisons.
806 // Don't use this macro directly in your code, use CHECK_STREQ et al below.
807 #define CHECK_STROP(func, op, expected, s1, s2) \
808 while (@ac_google_namespace@::CheckOpString _result = \
809 @ac_google_namespace@::Check##func##expected##Impl((s1), (s2), \
810 #s1 " " #op " " #s2)) \
811 LOG(FATAL) << *_result.str_
814 // String (char*) equality/inequality checks.
815 // CASE versions are case-insensitive.
817 // Note that "s1" and "s2" may be temporary strings which are destroyed
818 // by the compiler at the end of the current "full expression"
819 // (e.g. CHECK_STREQ(Foo().c_str(), Bar().c_str())).
821 #define CHECK_STREQ(s1, s2) CHECK_STROP(strcmp, ==, true, s1, s2)
822 #define CHECK_STRNE(s1, s2) CHECK_STROP(strcmp, !=, false, s1, s2)
823 #define CHECK_STRCASEEQ(s1, s2) CHECK_STROP(strcasecmp, ==, true, s1, s2)
824 #define CHECK_STRCASENE(s1, s2) CHECK_STROP(strcasecmp, !=, false, s1, s2)
826 #define CHECK_INDEX(I,A) CHECK(I < (sizeof(A)/sizeof(A[0])))
827 #define CHECK_BOUND(B,A) CHECK(B <= (sizeof(A)/sizeof(A[0])))
829 #define CHECK_DOUBLE_EQ(val1, val2) \
831 CHECK_LE((val1), (val2)+0.000000000000001L); \
832 CHECK_GE((val1), (val2)-0.000000000000001L); \
835 #define CHECK_NEAR(val1, val2, margin) \
837 CHECK_LE((val1), (val2)+(margin)); \
838 CHECK_GE((val1), (val2)-(margin)); \
841 // perror()..googly style!
843 // PLOG() and PLOG_IF() and PCHECK() behave exactly like their LOG* and
844 // CHECK equivalents with the addition that they postpend a description
845 // of the current state of errno to their output lines.
847 #define PLOG(severity) GOOGLE_PLOG(severity, 0).stream()
849 #define GOOGLE_PLOG(severity, counter) \
850 @ac_google_namespace@::ErrnoLogMessage( \
851 __FILE__, __LINE__, @ac_google_namespace@::GLOG_ ## severity, counter, \
852 &@ac_google_namespace@::LogMessage::SendToLog)
854 #define PLOG_IF(severity, condition) \
855 !(condition) ? (void) 0 : @ac_google_namespace@::LogMessageVoidify() & PLOG(severity)
857 // A CHECK() macro that postpends errno if the condition is false. E.g.
859 // if (poll(fds, nfds, timeout) == -1) { PCHECK(errno == EINTR); ... }
860 #define PCHECK(condition) \
861 PLOG_IF(FATAL, GOOGLE_PREDICT_BRANCH_NOT_TAKEN(!(condition))) \
862 << "Check failed: " #condition " "
864 // A CHECK() macro that lets you assert the success of a function that
865 // returns -1 and sets errno in case of an error. E.g.
867 // CHECK_ERR(mkdir(path, 0700));
871 // int fd = open(filename, flags); CHECK_ERR(fd) << ": open " << filename;
872 #define CHECK_ERR(invocation) \
873 PLOG_IF(FATAL, GOOGLE_PREDICT_BRANCH_NOT_TAKEN((invocation) == -1)) \
876 // Use macro expansion to create, for each use of LOG_EVERY_N(), static
877 // variables with the __LINE__ expansion as part of the variable name.
878 #define LOG_EVERY_N_VARNAME(base, line) LOG_EVERY_N_VARNAME_CONCAT(base, line)
879 #define LOG_EVERY_N_VARNAME_CONCAT(base, line) base ## line
881 #define LOG_OCCURRENCES LOG_EVERY_N_VARNAME(occurrences_, __LINE__)
882 #define LOG_OCCURRENCES_MOD_N LOG_EVERY_N_VARNAME(occurrences_mod_n_, __LINE__)
884 #define SOME_KIND_OF_LOG_EVERY_N(severity, n, what_to_do) \
885 static int LOG_OCCURRENCES = 0, LOG_OCCURRENCES_MOD_N = 0; \
887 if (++LOG_OCCURRENCES_MOD_N > n) LOG_OCCURRENCES_MOD_N -= n; \
888 if (LOG_OCCURRENCES_MOD_N == 1) \
889 @ac_google_namespace@::LogMessage( \
890 __FILE__, __LINE__, @ac_google_namespace@::GLOG_ ## severity, LOG_OCCURRENCES, \
891 &what_to_do).stream()
893 #define SOME_KIND_OF_LOG_IF_EVERY_N(severity, condition, n, what_to_do) \
894 static int LOG_OCCURRENCES = 0, LOG_OCCURRENCES_MOD_N = 0; \
897 ((LOG_OCCURRENCES_MOD_N=(LOG_OCCURRENCES_MOD_N + 1) % n) == (1 % n))) \
898 @ac_google_namespace@::LogMessage( \
899 __FILE__, __LINE__, @ac_google_namespace@::GLOG_ ## severity, LOG_OCCURRENCES, \
900 &what_to_do).stream()
902 #define SOME_KIND_OF_PLOG_EVERY_N(severity, n, what_to_do) \
903 static int LOG_OCCURRENCES = 0, LOG_OCCURRENCES_MOD_N = 0; \
905 if (++LOG_OCCURRENCES_MOD_N > n) LOG_OCCURRENCES_MOD_N -= n; \
906 if (LOG_OCCURRENCES_MOD_N == 1) \
907 @ac_google_namespace@::ErrnoLogMessage( \
908 __FILE__, __LINE__, @ac_google_namespace@::GLOG_ ## severity, LOG_OCCURRENCES, \
909 &what_to_do).stream()
911 #define SOME_KIND_OF_LOG_FIRST_N(severity, n, what_to_do) \
912 static int LOG_OCCURRENCES = 0; \
913 if (LOG_OCCURRENCES <= n) \
915 if (LOG_OCCURRENCES <= n) \
916 @ac_google_namespace@::LogMessage( \
917 __FILE__, __LINE__, @ac_google_namespace@::GLOG_ ## severity, LOG_OCCURRENCES, \
918 &what_to_do).stream()
920 namespace glog_internal_namespace_ {
922 struct CompileAssert {
925 } // namespace glog_internal_namespace_
927 #define GOOGLE_GLOG_COMPILE_ASSERT(expr, msg) \
928 typedef @ac_google_namespace@::glog_internal_namespace_::CompileAssert<(bool(expr))> msg[bool(expr) ? 1 : -1]
930 #define LOG_EVERY_N(severity, n) \
931 GOOGLE_GLOG_COMPILE_ASSERT(@ac_google_namespace@::GLOG_ ## severity < \
932 @ac_google_namespace@::NUM_SEVERITIES, \
933 INVALID_REQUESTED_LOG_SEVERITY); \
934 SOME_KIND_OF_LOG_EVERY_N(severity, (n), @ac_google_namespace@::LogMessage::SendToLog)
936 #define SYSLOG_EVERY_N(severity, n) \
937 SOME_KIND_OF_LOG_EVERY_N(severity, (n), @ac_google_namespace@::LogMessage::SendToSyslogAndLog)
939 #define PLOG_EVERY_N(severity, n) \
940 SOME_KIND_OF_PLOG_EVERY_N(severity, (n), @ac_google_namespace@::LogMessage::SendToLog)
942 #define LOG_FIRST_N(severity, n) \
943 SOME_KIND_OF_LOG_FIRST_N(severity, (n), @ac_google_namespace@::LogMessage::SendToLog)
945 #define LOG_IF_EVERY_N(severity, condition, n) \
946 SOME_KIND_OF_LOG_IF_EVERY_N(severity, (condition), (n), @ac_google_namespace@::LogMessage::SendToLog)
948 // We want the special COUNTER value available for LOG_EVERY_X()'ed messages
949 enum PRIVATE_Counter {COUNTER};
951 #ifdef GLOG_NO_ABBREVIATED_SEVERITIES
952 // wingdi.h defines ERROR to be 0. When we call LOG(ERROR), it gets
953 // substituted with 0, and it expands to COMPACT_GOOGLE_LOG_0. To allow us
954 // to keep using this syntax, we define this macro to do the same thing
955 // as COMPACT_GOOGLE_LOG_ERROR.
956 #define COMPACT_GOOGLE_LOG_0 COMPACT_GOOGLE_LOG_ERROR
957 #define SYSLOG_0 SYSLOG_ERROR
958 #define LOG_TO_STRING_0 LOG_TO_STRING_ERROR
959 // Needed for LOG_IS_ON(ERROR).
960 const LogSeverity GLOG_0 = GLOG_ERROR;
962 // Users may include windows.h after logging.h without
963 // GLOG_NO_ABBREVIATED_SEVERITIES nor WIN32_LEAN_AND_MEAN.
964 // For this case, we cannot detect if ERROR is defined before users
965 // actually use ERROR. Let's make an undefined symbol to warn users.
966 # define GLOG_ERROR_MSG ERROR_macro_is_defined_Define_GLOG_NO_ABBREVIATED_SEVERITIES_before_including_logging_h_See_the_document_for_detail
967 # define COMPACT_GOOGLE_LOG_0 GLOG_ERROR_MSG
968 # define SYSLOG_0 GLOG_ERROR_MSG
969 # define LOG_TO_STRING_0 GLOG_ERROR_MSG
970 # define GLOG_0 GLOG_ERROR_MSG
973 // Plus some debug-logging macros that get compiled to nothing for production
977 #define DLOG(severity) LOG(severity)
978 #define DVLOG(verboselevel) VLOG(verboselevel)
979 #define DLOG_IF(severity, condition) LOG_IF(severity, condition)
980 #define DLOG_EVERY_N(severity, n) LOG_EVERY_N(severity, n)
981 #define DLOG_IF_EVERY_N(severity, condition, n) \
982 LOG_IF_EVERY_N(severity, condition, n)
983 #define DLOG_ASSERT(condition) LOG_ASSERT(condition)
985 // debug-only checking. not executed in NDEBUG mode.
986 #define DCHECK(condition) CHECK(condition)
987 #define DCHECK_EQ(val1, val2) CHECK_EQ(val1, val2)
988 #define DCHECK_NE(val1, val2) CHECK_NE(val1, val2)
989 #define DCHECK_LE(val1, val2) CHECK_LE(val1, val2)
990 #define DCHECK_LT(val1, val2) CHECK_LT(val1, val2)
991 #define DCHECK_GE(val1, val2) CHECK_GE(val1, val2)
992 #define DCHECK_GT(val1, val2) CHECK_GT(val1, val2)
993 #define DCHECK_NOTNULL(val) CHECK_NOTNULL(val)
994 #define DCHECK_STREQ(str1, str2) CHECK_STREQ(str1, str2)
995 #define DCHECK_STRCASEEQ(str1, str2) CHECK_STRCASEEQ(str1, str2)
996 #define DCHECK_STRNE(str1, str2) CHECK_STRNE(str1, str2)
997 #define DCHECK_STRCASENE(str1, str2) CHECK_STRCASENE(str1, str2)
1001 #define DLOG(severity) \
1002 true ? (void) 0 : @ac_google_namespace@::LogMessageVoidify() & LOG(severity)
1004 #define DVLOG(verboselevel) \
1005 (true || !VLOG_IS_ON(verboselevel)) ?\
1006 (void) 0 : @ac_google_namespace@::LogMessageVoidify() & LOG(INFO)
1008 #define DLOG_IF(severity, condition) \
1009 (true || !(condition)) ? (void) 0 : @ac_google_namespace@::LogMessageVoidify() & LOG(severity)
1011 #define DLOG_EVERY_N(severity, n) \
1012 true ? (void) 0 : @ac_google_namespace@::LogMessageVoidify() & LOG(severity)
1014 #define DLOG_IF_EVERY_N(severity, condition, n) \
1015 (true || !(condition))? (void) 0 : @ac_google_namespace@::LogMessageVoidify() & LOG(severity)
1017 #define DLOG_ASSERT(condition) \
1018 true ? (void) 0 : LOG_ASSERT(condition)
1020 // MSVC warning C4127: conditional expression is constant
1021 #define DCHECK(condition) \
1022 GLOG_MSVC_PUSH_DISABLE_WARNING(4127) \
1024 GLOG_MSVC_POP_WARNING() CHECK(condition)
1026 #define DCHECK_EQ(val1, val2) \
1027 GLOG_MSVC_PUSH_DISABLE_WARNING(4127) \
1029 GLOG_MSVC_POP_WARNING() CHECK_EQ(val1, val2)
1031 #define DCHECK_NE(val1, val2) \
1032 GLOG_MSVC_PUSH_DISABLE_WARNING(4127) \
1034 GLOG_MSVC_POP_WARNING() CHECK_NE(val1, val2)
1036 #define DCHECK_LE(val1, val2) \
1037 GLOG_MSVC_PUSH_DISABLE_WARNING(4127) \
1039 GLOG_MSVC_POP_WARNING() CHECK_LE(val1, val2)
1041 #define DCHECK_LT(val1, val2) \
1042 GLOG_MSVC_PUSH_DISABLE_WARNING(4127) \
1044 GLOG_MSVC_POP_WARNING() CHECK_LT(val1, val2)
1046 #define DCHECK_GE(val1, val2) \
1047 GLOG_MSVC_PUSH_DISABLE_WARNING(4127) \
1049 GLOG_MSVC_POP_WARNING() CHECK_GE(val1, val2)
1051 #define DCHECK_GT(val1, val2) \
1052 GLOG_MSVC_PUSH_DISABLE_WARNING(4127) \
1054 GLOG_MSVC_POP_WARNING() CHECK_GT(val1, val2)
1056 // You may see warnings in release mode if you don't use the return
1057 // value of DCHECK_NOTNULL. Please just use DCHECK for such cases.
1058 #define DCHECK_NOTNULL(val) (val)
1060 #define DCHECK_STREQ(str1, str2) \
1061 GLOG_MSVC_PUSH_DISABLE_WARNING(4127) \
1063 GLOG_MSVC_POP_WARNING() CHECK_STREQ(str1, str2)
1065 #define DCHECK_STRCASEEQ(str1, str2) \
1066 GLOG_MSVC_PUSH_DISABLE_WARNING(4127) \
1068 GLOG_MSVC_POP_WARNING() CHECK_STRCASEEQ(str1, str2)
1070 #define DCHECK_STRNE(str1, str2) \
1071 GLOG_MSVC_PUSH_DISABLE_WARNING(4127) \
1073 GLOG_MSVC_POP_WARNING() CHECK_STRNE(str1, str2)
1075 #define DCHECK_STRCASENE(str1, str2) \
1076 GLOG_MSVC_PUSH_DISABLE_WARNING(4127) \
1078 GLOG_MSVC_POP_WARNING() CHECK_STRCASENE(str1, str2)
1082 // Log only in verbose mode.
1084 #define VLOG(verboselevel) LOG_IF(INFO, VLOG_IS_ON(verboselevel))
1086 #define VLOG_IF(verboselevel, condition) \
1087 LOG_IF(INFO, (condition) && VLOG_IS_ON(verboselevel))
1089 #define VLOG_EVERY_N(verboselevel, n) \
1090 LOG_IF_EVERY_N(INFO, VLOG_IS_ON(verboselevel), n)
1092 #define VLOG_IF_EVERY_N(verboselevel, condition, n) \
1093 LOG_IF_EVERY_N(INFO, (condition) && VLOG_IS_ON(verboselevel), n)
1095 namespace base_logging {
1097 // LogMessage::LogStream is a std::ostream backed by this streambuf.
1098 // This class ignores overflow and leaves two bytes at the end of the
1099 // buffer to allow for a '\n' and '\0'.
1100 class GOOGLE_GLOG_DLL_DECL LogStreamBuf : public std::streambuf {
1102 // REQUIREMENTS: "len" must be >= 2 to account for the '\n' and '\n'.
1103 LogStreamBuf(char *buf, int len) {
1104 setp(buf, buf + len - 2);
1106 // This effectively ignores overflow.
1107 virtual int_type overflow(int_type ch) {
1111 // Legacy public ostrstream method.
1112 size_t pcount() const { return pptr() - pbase(); }
1113 char* pbase() const { return std::streambuf::pbase(); }
1116 } // namespace base_logging
1119 // This class more or less represents a particular log message. You
1120 // create an instance of LogMessage and then stream stuff to it.
1121 // When you finish streaming to it, ~LogMessage is called and the
1122 // full message gets streamed to the appropriate destination.
1124 // You shouldn't actually use LogMessage's constructor to log things,
1125 // though. You should use the LOG() macro (and variants thereof)
1127 class GOOGLE_GLOG_DLL_DECL LogMessage {
1130 // Passing kNoLogPrefix for the line number disables the
1131 // log-message prefix. Useful for using the LogMessage
1132 // infrastructure as a printing utility. See also the --log_prefix
1133 // flag for controlling the log-message prefix on an
1134 // application-wide basis.
1138 // LogStream inherit from non-DLL-exported class (std::ostrstream)
1139 // and VC++ produces a warning for this situation.
1140 // However, MSDN says "C4275 can be ignored in Microsoft Visual C++
1141 // 2005 if you are deriving from a type in the Standard C++ Library"
1142 // http://msdn.microsoft.com/en-us/library/3tdb471s(VS.80).aspx
1143 // Let's just ignore the warning.
1145 # pragma warning(disable: 4275)
1147 class GOOGLE_GLOG_DLL_DECL LogStream : public std::ostream {
1149 # pragma warning(default: 4275)
1152 LogStream(char *buf, int len, int ctr)
1153 : std::ostream(NULL),
1154 streambuf_(buf, len),
1160 int ctr() const { return ctr_; }
1161 void set_ctr(int ctr) { ctr_ = ctr; }
1162 LogStream* self() const { return self_; }
1164 // Legacy std::streambuf methods.
1165 size_t pcount() const { return streambuf_.pcount(); }
1166 char* pbase() const { return streambuf_.pbase(); }
1167 char* str() const { return pbase(); }
1170 base_logging::LogStreamBuf streambuf_;
1171 int ctr_; // Counter hack (for the LOG_EVERY_X() macro)
1172 LogStream *self_; // Consistency check hack
1176 // icc 8 requires this typedef to avoid an internal compiler error.
1177 typedef void (LogMessage::*SendMethod)();
1179 LogMessage(const char* file, int line, LogSeverity severity, int ctr,
1180 SendMethod send_method);
1182 // Two special constructors that generate reduced amounts of code at
1183 // LOG call sites for common cases.
1185 // Used for LOG(INFO): Implied are:
1186 // severity = INFO, ctr = 0, send_method = &LogMessage::SendToLog.
1188 // Using this constructor instead of the more complex constructor above
1189 // saves 19 bytes per call site.
1190 LogMessage(const char* file, int line);
1192 // Used for LOG(severity) where severity != INFO. Implied
1193 // are: ctr = 0, send_method = &LogMessage::SendToLog
1195 // Using this constructor instead of the more complex constructor above
1196 // saves 17 bytes per call site.
1197 LogMessage(const char* file, int line, LogSeverity severity);
1199 // Constructor to log this message to a specified sink (if not NULL).
1200 // Implied are: ctr = 0, send_method = &LogMessage::SendToSinkAndLog if
1201 // also_send_to_log is true, send_method = &LogMessage::SendToSink otherwise.
1202 LogMessage(const char* file, int line, LogSeverity severity, LogSink* sink,
1203 bool also_send_to_log);
1205 // Constructor where we also give a vector<string> pointer
1206 // for storing the messages (if the pointer is not NULL).
1207 // Implied are: ctr = 0, send_method = &LogMessage::SaveOrSendToLog.
1208 LogMessage(const char* file, int line, LogSeverity severity,
1209 std::vector<std::string>* outvec);
1211 // Constructor where we also give a string pointer for storing the
1212 // message (if the pointer is not NULL). Implied are: ctr = 0,
1213 // send_method = &LogMessage::WriteToStringAndLog.
1214 LogMessage(const char* file, int line, LogSeverity severity,
1215 std::string* message);
1217 // A special constructor used for check failures
1218 LogMessage(const char* file, int line, const CheckOpString& result);
1222 // Flush a buffered message to the sink set in the constructor. Always
1223 // called by the destructor, it may also be called from elsewhere if
1224 // needed. Only the first call is actioned; any later ones are ignored.
1227 // An arbitrary limit on the length of a single log message. This
1228 // is so that streaming can be done more efficiently.
1229 static const size_t kMaxLogMessageLen;
1231 // Theses should not be called directly outside of logging.*,
1232 // only passed as SendMethod arguments to other LogMessage methods:
1233 void SendToLog(); // Actually dispatch to the logs
1234 void SendToSyslogAndLog(); // Actually dispatch to syslog and the logs
1236 // Call abort() or similar to perform LOG(FATAL) crash.
1237 static void Fail() @ac_cv___attribute___noreturn@;
1239 std::ostream& stream();
1241 int preserved_errno() const;
1243 // Must be called without the log_mutex held. (L < log_mutex)
1244 static int64 num_messages(int severity);
1246 struct LogMessageData;
1249 // Fully internal SendMethod cases:
1250 void SendToSinkAndLog(); // Send to sink if provided and dispatch to the logs
1251 void SendToSink(); // Send to sink if provided, do nothing otherwise.
1253 // Write to string if provided and dispatch to the logs.
1254 void WriteToStringAndLog();
1256 void SaveOrSendToLog(); // Save to stringvec if provided, else to logs
1258 void Init(const char* file, int line, LogSeverity severity,
1259 void (LogMessage::*send_method)());
1261 // Used to fill in crash information during LOG(FATAL) failures.
1262 void RecordCrashReason(glog_internal_namespace_::CrashReason* reason);
1264 // Counts of messages sent at each priority:
1265 static int64 num_messages_[NUM_SEVERITIES]; // under log_mutex
1267 // We keep the data in a separate struct so that each instance of
1268 // LogMessage uses less stack space.
1269 LogMessageData* allocated_;
1270 LogMessageData* data_;
1272 friend class LogDestination;
1274 LogMessage(const LogMessage&);
1275 void operator=(const LogMessage&);
1278 // This class happens to be thread-hostile because all instances share
1279 // a single data buffer, but since it can only be created just before
1280 // the process dies, we don't worry so much.
1281 class GOOGLE_GLOG_DLL_DECL LogMessageFatal : public LogMessage {
1283 LogMessageFatal(const char* file, int line);
1284 LogMessageFatal(const char* file, int line, const CheckOpString& result);
1285 ~LogMessageFatal() @ac_cv___attribute___noreturn@;
1288 // A non-macro interface to the log facility; (useful
1289 // when the logging level is not a compile-time constant).
1290 inline void LogAtLevel(int const severity, std::string const &msg) {
1291 LogMessage(__FILE__, __LINE__, severity).stream() << msg;
1294 // A macro alternative of LogAtLevel. New code may want to use this
1295 // version since there are two advantages: 1. this version outputs the
1296 // file name and the line number where this macro is put like other
1297 // LOG macros, 2. this macro can be used as C++ stream.
1298 #define LOG_AT_LEVEL(severity) @ac_google_namespace@::LogMessage(__FILE__, __LINE__, severity).stream()
1300 // A small helper for CHECK_NOTNULL().
1301 template <typename T>
1302 T* CheckNotNull(const char *file, int line, const char *names, T* t) {
1304 LogMessageFatal(file, line, new std::string(names));
1309 // Allow folks to put a counter in the LOG_EVERY_X()'ed messages. This
1310 // only works if ostream is a LogStream. If the ostream is not a
1311 // LogStream you'll get an assert saying as much at runtime.
1312 GOOGLE_GLOG_DLL_DECL std::ostream& operator<<(std::ostream &os,
1313 const PRIVATE_Counter&);
1316 // Derived class for PLOG*() above.
1317 class GOOGLE_GLOG_DLL_DECL ErrnoLogMessage : public LogMessage {
1320 ErrnoLogMessage(const char* file, int line, LogSeverity severity, int ctr,
1321 void (LogMessage::*send_method)());
1323 // Postpends ": strerror(errno) [errno]".
1327 ErrnoLogMessage(const ErrnoLogMessage&);
1328 void operator=(const ErrnoLogMessage&);
1332 // This class is used to explicitly ignore values in the conditional
1333 // logging macros. This avoids compiler warnings like "value computed
1334 // is not used" and "statement has no effect".
1336 class GOOGLE_GLOG_DLL_DECL LogMessageVoidify {
1338 LogMessageVoidify() { }
1339 // This has to be an operator with a precedence lower than << but
1341 void operator&(std::ostream&) { }
1345 // Flushes all log files that contains messages that are at least of
1346 // the specified severity level. Thread-safe.
1347 GOOGLE_GLOG_DLL_DECL void FlushLogFiles(LogSeverity min_severity);
1349 // Flushes all log files that contains messages that are at least of
1350 // the specified severity level. Thread-hostile because it ignores
1351 // locking -- used for catastrophic failures.
1352 GOOGLE_GLOG_DLL_DECL void FlushLogFilesUnsafe(LogSeverity min_severity);
1355 // Set the destination to which a particular severity level of log
1356 // messages is sent. If base_filename is "", it means "don't log this
1357 // severity". Thread-safe.
1359 GOOGLE_GLOG_DLL_DECL void SetLogDestination(LogSeverity severity,
1360 const char* base_filename);
1363 // Set the basename of the symlink to the latest log file at a given
1364 // severity. If symlink_basename is empty, do not make a symlink. If
1365 // you don't call this function, the symlink basename is the
1366 // invocation name of the program. Thread-safe.
1368 GOOGLE_GLOG_DLL_DECL void SetLogSymlink(LogSeverity severity,
1369 const char* symlink_basename);
1372 // Used to send logs to some other kind of destination
1373 // Users should subclass LogSink and override send to do whatever they want.
1374 // Implementations must be thread-safe because a shared instance will
1375 // be called from whichever thread ran the LOG(XXX) line.
1376 class GOOGLE_GLOG_DLL_DECL LogSink {
1380 // Sink's logging logic (message_len is such as to exclude '\n' at the end).
1381 // This method can't use LOG() or CHECK() as logging system mutex(s) are held
1382 // during this call.
1383 virtual void send(LogSeverity severity, const char* full_filename,
1384 const char* base_filename, int line,
1385 const struct ::tm* tm_time,
1386 const char* message, size_t message_len) = 0;
1388 // Redefine this to implement waiting for
1389 // the sink's logging logic to complete.
1390 // It will be called after each send() returns,
1391 // but before that LogMessage exits or crashes.
1392 // By default this function does nothing.
1393 // Using this function one can implement complex logic for send()
1394 // that itself involves logging; and do all this w/o causing deadlocks and
1395 // inconsistent rearrangement of log messages.
1396 // E.g. if a LogSink has thread-specific actions, the send() method
1397 // can simply add the message to a queue and wake up another thread that
1398 // handles real logging while itself making some LOG() calls;
1399 // WaitTillSent() can be implemented to wait for that logic to complete.
1400 // See our unittest for an example.
1401 virtual void WaitTillSent();
1403 // Returns the normal text output of the log message.
1404 // Can be useful to implement send().
1405 static std::string ToString(LogSeverity severity, const char* file, int line,
1406 const struct ::tm* tm_time,
1407 const char* message, size_t message_len);
1410 // Add or remove a LogSink as a consumer of logging data. Thread-safe.
1411 GOOGLE_GLOG_DLL_DECL void AddLogSink(LogSink *destination);
1412 GOOGLE_GLOG_DLL_DECL void RemoveLogSink(LogSink *destination);
1415 // Specify an "extension" added to the filename specified via
1416 // SetLogDestination. This applies to all severity levels. It's
1417 // often used to append the port we're listening on to the logfile
1418 // name. Thread-safe.
1420 GOOGLE_GLOG_DLL_DECL void SetLogFilenameExtension(
1421 const char* filename_extension);
1424 // Make it so that all log messages of at least a particular severity
1425 // are logged to stderr (in addition to logging to the usual log
1426 // file(s)). Thread-safe.
1428 GOOGLE_GLOG_DLL_DECL void SetStderrLogging(LogSeverity min_severity);
1431 // Make it so that all log messages go only to stderr. Thread-safe.
1433 GOOGLE_GLOG_DLL_DECL void LogToStderr();
1436 // Make it so that all log messages of at least a particular severity are
1437 // logged via email to a list of addresses (in addition to logging to the
1438 // usual log file(s)). The list of addresses is just a string containing
1439 // the email addresses to send to (separated by spaces, say). Thread-safe.
1441 GOOGLE_GLOG_DLL_DECL void SetEmailLogging(LogSeverity min_severity,
1442 const char* addresses);
1444 // A simple function that sends email. dest is a commma-separated
1445 // list of addressess. Thread-safe.
1446 GOOGLE_GLOG_DLL_DECL bool SendEmail(const char *dest,
1447 const char *subject, const char *body);
1449 GOOGLE_GLOG_DLL_DECL const std::vector<std::string>& GetLoggingDirectories();
1451 // For tests only: Clear the internal [cached] list of logging directories to
1452 // force a refresh the next time GetLoggingDirectories is called.
1454 void TestOnly_ClearLoggingDirectoriesList();
1456 // Returns a set of existing temporary directories, which will be a
1457 // subset of the directories returned by GetLogginDirectories().
1459 GOOGLE_GLOG_DLL_DECL void GetExistingTempDirectories(
1460 std::vector<std::string>* list);
1462 // Print any fatal message again -- useful to call from signal handler
1463 // so that the last thing in the output is the fatal message.
1464 // Thread-hostile, but a race is unlikely.
1465 GOOGLE_GLOG_DLL_DECL void ReprintFatalMessage();
1467 // Truncate a log file that may be the append-only output of multiple
1468 // processes and hence can't simply be renamed/reopened (typically a
1469 // stdout/stderr). If the file "path" is > "limit" bytes, copy the
1470 // last "keep" bytes to offset 0 and truncate the rest. Since we could
1471 // be racing with other writers, this approach has the potential to
1472 // lose very small amounts of data. For security, only follow symlinks
1473 // if the path is /proc/self/fd/*
1474 GOOGLE_GLOG_DLL_DECL void TruncateLogFile(const char *path,
1475 int64 limit, int64 keep);
1477 // Truncate stdout and stderr if they are over the value specified by
1478 // --max_log_size; keep the final 1MB. This function has the same
1479 // race condition as TruncateLogFile.
1480 GOOGLE_GLOG_DLL_DECL void TruncateStdoutStderr();
1482 // Return the string representation of the provided LogSeverity level.
1484 GOOGLE_GLOG_DLL_DECL const char* GetLogSeverityName(LogSeverity severity);
1486 // ---------------------------------------------------------------------
1487 // Implementation details that are not useful to most clients
1488 // ---------------------------------------------------------------------
1490 // A Logger is the interface used by logging modules to emit entries
1491 // to a log. A typical implementation will dump formatted data to a
1492 // sequence of files. We also provide interfaces that will forward
1493 // the data to another thread so that the invoker never blocks.
1494 // Implementations should be thread-safe since the logging system
1495 // will write to them from multiple threads.
1499 class GOOGLE_GLOG_DLL_DECL Logger {
1503 // Writes "message[0,message_len-1]" corresponding to an event that
1504 // occurred at "timestamp". If "force_flush" is true, the log file
1505 // is flushed immediately.
1507 // The input message has already been formatted as deemed
1508 // appropriate by the higher level logging facility. For example,
1509 // textual log messages already contain timestamps, and the
1510 // file:linenumber header.
1511 virtual void Write(bool force_flush,
1513 const char* message,
1514 int message_len) = 0;
1516 // Flush any buffered messages
1517 virtual void Flush() = 0;
1519 // Get the current LOG file size.
1520 // The returned value is approximate since some
1521 // logged data may not have been flushed to disk yet.
1522 virtual uint32 LogSize() = 0;
1525 // Get the logger for the specified severity level. The logger
1526 // remains the property of the logging module and should not be
1527 // deleted by the caller. Thread-safe.
1528 extern GOOGLE_GLOG_DLL_DECL Logger* GetLogger(LogSeverity level);
1530 // Set the logger for the specified severity level. The logger
1531 // becomes the property of the logging module and should not
1532 // be deleted by the caller. Thread-safe.
1533 extern GOOGLE_GLOG_DLL_DECL void SetLogger(LogSeverity level, Logger* logger);
1537 // glibc has traditionally implemented two incompatible versions of
1538 // strerror_r(). There is a poorly defined convention for picking the
1539 // version that we want, but it is not clear whether it even works with
1540 // all versions of glibc.
1541 // So, instead, we provide this wrapper that automatically detects the
1542 // version that is in use, and then implements POSIX semantics.
1543 // N.B. In addition to what POSIX says, we also guarantee that "buf" will
1544 // be set to an empty string, if this function failed. This means, in most
1545 // cases, you do not need to check the error code and you can directly
1546 // use the value of "buf". It will never have an undefined value.
1547 // DEPRECATED: Use StrError(int) instead.
1548 GOOGLE_GLOG_DLL_DECL int posix_strerror_r(int err, char *buf, size_t len);
1550 // A thread-safe replacement for strerror(). Returns a string describing the
1551 // given POSIX error code.
1552 GOOGLE_GLOG_DLL_DECL std::string StrError(int err);
1554 // A class for which we define operator<<, which does nothing.
1555 class GOOGLE_GLOG_DLL_DECL NullStream : public LogMessage::LogStream {
1557 // Initialize the LogStream so the messages can be written somewhere
1558 // (they'll never be actually displayed). This will be needed if a
1559 // NullStream& is implicitly converted to LogStream&, in which case
1560 // the overloaded NullStream::operator<< will not be invoked.
1561 NullStream() : LogMessage::LogStream(message_buffer_, 1, 0) { }
1562 NullStream(const char* /*file*/, int /*line*/,
1563 const CheckOpString& /*result*/) :
1564 LogMessage::LogStream(message_buffer_, 1, 0) { }
1565 NullStream &stream() { return *this; }
1567 // A very short buffer for messages (which we discard anyway). This
1568 // will be needed if NullStream& converted to LogStream& (e.g. as a
1569 // result of a conditional expression).
1570 char message_buffer_[2];
1573 // Do nothing. This operator is inline, allowing the message to be
1574 // compiled away. The message will not be compiled away if we do
1575 // something like (flag ? LOG(INFO) : LOG(ERROR)) << message; when
1576 // SKIP_LOG=WARNING. In those cases, NullStream will be implicitly
1577 // converted to LogStream and the message will be computed and then
1578 // quietly discarded.
1580 inline NullStream& operator<<(NullStream &str, const T &) { return str; }
1582 // Similar to NullStream, but aborts the program (without stack
1583 // trace), like LogMessageFatal.
1584 class GOOGLE_GLOG_DLL_DECL NullStreamFatal : public NullStream {
1586 NullStreamFatal() { }
1587 NullStreamFatal(const char* file, int line, const CheckOpString& result) :
1588 NullStream(file, line, result) { }
1589 @ac_cv___attribute___noreturn@ ~NullStreamFatal() { _exit(1); }
1592 // Install a signal handler that will dump signal information and a stack
1593 // trace when the program crashes on certain signals. We'll install the
1594 // signal handler for the following signals.
1596 // SIGSEGV, SIGILL, SIGFPE, SIGABRT, SIGBUS, and SIGTERM.
1598 // By default, the signal handler will write the failure dump to the
1599 // standard error. You can customize the destination by installing your
1600 // own writer function by InstallFailureWriter() below.
1602 // Note on threading:
1604 // The function should be called before threads are created, if you want
1605 // to use the failure signal handler for all threads. The stack trace
1606 // will be shown only for the thread that receives the signal. In other
1607 // words, stack traces of other threads won't be shown.
1608 GOOGLE_GLOG_DLL_DECL void InstallFailureSignalHandler();
1610 // Installs a function that is used for writing the failure dump. "data"
1611 // is the pointer to the beginning of a message to be written, and "size"
1612 // is the size of the message. You should not expect the data is
1613 // terminated with '\0'.
1614 GOOGLE_GLOG_DLL_DECL void InstallFailureWriter(
1615 void (*writer)(const char* data, int size));
1617 @ac_google_end_namespace@
1619 #endif // _LOGGING_H_