1 // This file is automatically generated from src/glog/logging.h.in
2 // using src/windows/preprocess.sh.
5 // Copyright (c) 1999, Google Inc.
6 // All rights reserved.
8 // Redistribution and use in source and binary forms, with or without
9 // modification, are permitted provided that the following conditions are
12 // * Redistributions of source code must retain the above copyright
13 // notice, this list of conditions and the following disclaimer.
14 // * Redistributions in binary form must reproduce the above
15 // copyright notice, this list of conditions and the following disclaimer
16 // in the documentation and/or other materials provided with the
18 // * Neither the name of Google Inc. nor the names of its
19 // contributors may be used to endorse or promote products derived from
20 // this software without specific prior written permission.
22 // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
23 // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
24 // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
25 // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
26 // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
27 // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
28 // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
29 // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
30 // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
31 // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
32 // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
36 // This file contains #include information about logging-related stuff.
37 // Pretty much everybody needs to #include this file so that they can
38 // log various happenings.
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).
76 #include <stdint.h> // the normal place uint16_t is defined
79 #include <sys/types.h> // the normal place u_int16_t is defined
82 #include <inttypes.h> // a third place for uint16_t or u_int16_t
86 #include <gflags/gflags.h>
91 #if 0 // 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 0 // 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 1 // 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
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
132 #define GOOGLE_PREDICT_BRANCH_NOT_TAKEN(x) (__builtin_expect(x, 0))
134 #define GOOGLE_PREDICT_BRANCH_NOT_TAKEN(x) x
138 // Make a bunch of macros for logging. The way to log things is to stream
139 // things to LOG(<a particular severity level>). E.g.,
141 // LOG(INFO) << "Found " << num_cookies << " cookies";
143 // You can capture log messages in a string, rather than reporting them
146 // vector<string> errors;
147 // LOG_STRING(ERROR, &errors) << "Couldn't parse cookie #" << cookie_num;
149 // This pushes back the new error onto 'errors'; if given a NULL pointer,
150 // it reports the error via LOG(ERROR).
152 // You can also do conditional logging:
154 // LOG_IF(INFO, num_cookies > 10) << "Got lots of cookies";
156 // You can also do occasional logging (log every n'th occurrence of an
159 // LOG_EVERY_N(INFO, 10) << "Got the " << google::COUNTER << "th cookie";
161 // The above will cause log messages to be output on the 1st, 11th, 21st, ...
162 // times it is executed. Note that the special google::COUNTER value is used
163 // to identify which repetition is happening.
165 // You can also do occasional conditional logging (log every n'th
166 // occurrence of an event, when condition is satisfied):
168 // LOG_IF_EVERY_N(INFO, (size > 1024), 10) << "Got the " << google::COUNTER
169 // << "th big cookie";
171 // You can log messages the first N times your code executes a line. E.g.
173 // LOG_FIRST_N(INFO, 20) << "Got the " << google::COUNTER << "th cookie";
175 // Outputs log messages for the first 20 times it is executed.
177 // Analogous SYSLOG, SYSLOG_IF, and SYSLOG_EVERY_N macros are available.
178 // These log to syslog as well as to the normal logs. If you use these at
179 // all, you need to be aware that syslog can drastically reduce performance,
180 // especially if it is configured for remote logging! Don't use these
181 // unless you fully understand this and have a concrete need to use them.
182 // Even then, try to minimize your use of them.
184 // There are also "debug mode" logging macros like the ones above:
186 // DLOG(INFO) << "Found cookies";
188 // DLOG_IF(INFO, num_cookies > 10) << "Got lots of cookies";
190 // DLOG_EVERY_N(INFO, 10) << "Got the " << google::COUNTER << "th cookie";
192 // All "debug mode" logging is compiled away to nothing for non-debug mode
197 // LOG_ASSERT(assertion);
198 // DLOG_ASSERT(assertion);
200 // which is syntactic sugar for {,D}LOG_IF(FATAL, assert fails) << assertion;
202 // There are "verbose level" logging macros. They look like
204 // VLOG(1) << "I'm printed when you run the program with --v=1 or more";
205 // VLOG(2) << "I'm printed when you run the program with --v=2 or more";
207 // These always log at the INFO log level (when they log at all).
208 // The verbose logging can also be turned on module-by-module. For instance,
209 // --vmodule=mapreduce=2,file=1,gfs*=3 --v=0
211 // a. VLOG(2) and lower messages to be printed from mapreduce.{h,cc}
212 // b. VLOG(1) and lower messages to be printed from file.{h,cc}
213 // c. VLOG(3) and lower messages to be printed from files prefixed with "gfs"
214 // d. VLOG(0) and lower messages to be printed from elsewhere
216 // The wildcarding functionality shown by (c) supports both '*' (match
217 // 0 or more characters) and '?' (match any single character) wildcards.
219 // There's also VLOG_IS_ON(n) "verbose level" condition macro. To be used as
221 // if (VLOG_IS_ON(2)) {
222 // // do some logging preparation and logging
223 // // that can't be accomplished with just VLOG(2) << ...;
226 // There are also VLOG_IF, VLOG_EVERY_N and VLOG_IF_EVERY_N "verbose level"
227 // condition macros for sample cases, when some extra computation and
228 // preparation for logs is not needed.
229 // VLOG_IF(1, (size > 1024))
230 // << "I'm printed when size is more than 1024 and when you run the "
231 // "program with --v=1 or more";
232 // VLOG_EVERY_N(1, 10)
233 // << "I'm printed every 10th occurrence, and when you run the program "
234 // "with --v=1 or more. Present occurence is " << google::COUNTER;
235 // VLOG_IF_EVERY_N(1, (size > 1024), 10)
236 // << "I'm printed on every 10th occurence of case when size is more "
237 // " than 1024, when you run the program with --v=1 or more. ";
238 // "Present occurence is " << google::COUNTER;
240 // The supported severity levels for macros that allow you to specify one
241 // are (in increasing order of severity) INFO, WARNING, ERROR, and FATAL.
242 // Note that messages of a given severity are logged not only in the
243 // logfile for that severity, but also in all logfiles of lower severity.
244 // E.g., a message of severity FATAL will be logged to the logfiles of
245 // severity FATAL, ERROR, WARNING, and INFO.
247 // There is also the special severity of DFATAL, which logs FATAL in
248 // debug mode, ERROR in normal mode.
250 // Very important: logging a message at the FATAL severity level causes
251 // the program to terminate (after the message is logged).
253 // Unless otherwise specified, logs will be written to the filename
254 // "<program name>.<hostname>.<user name>.log.<severity level>.", followed
255 // by the date, time, and pid (you can't prevent the date, time, and pid
256 // from being in the filename).
258 // The logging code takes two flags:
259 // --v=# set the verbose level
260 // --logtostderr log all the messages to stderr instead of to logfiles
262 // LOG LINE PREFIX FORMAT
264 // Log lines have this form:
266 // Lmmdd hh:mm:ss.uuuuuu threadid file:line] msg...
268 // where the fields are defined as follows:
270 // L A single character, representing the log level
272 // mm The month (zero padded; ie May is '05')
273 // dd The day (zero padded)
274 // hh:mm:ss.uuuuuu Time in hours, minutes and fractional seconds
275 // threadid The space-padded thread ID as returned by GetTID()
276 // (this matches the PID on Linux)
277 // file The file name
278 // line The line number
279 // msg The user-supplied message
283 // I1103 11:57:31.739339 24395 google.cc:2341] Command line: ./some_prog
284 // I1103 11:57:31.739403 24395 google.cc:2342] Process id 24395
286 // NOTE: although the microseconds are useful for comparing events on
287 // a single machine, clocks on different machines may not be well
288 // synchronized. Hence, use caution when comparing the low bits of
289 // timestamps from different machines.
291 #ifndef DECLARE_VARIABLE
292 #define MUST_UNDEF_GFLAGS_DECLARE_MACROS
293 #define DECLARE_VARIABLE(type, name, tn) \
294 namespace FLAG__namespace_do_not_use_directly_use_DECLARE_##tn##_instead { \
295 extern GOOGLE_GLOG_DLL_DECL type FLAGS_##name; \
297 using FLAG__namespace_do_not_use_directly_use_DECLARE_##tn##_instead::FLAGS_##name
299 // bool specialization
300 #define DECLARE_bool(name) \
301 DECLARE_VARIABLE(bool, name, bool)
303 // int32 specialization
304 #define DECLARE_int32(name) \
305 DECLARE_VARIABLE(google::int32, name, int32)
307 // Special case for string, because we have to specify the namespace
308 // std::string, which doesn't play nicely with our FLAG__namespace hackery.
309 #define DECLARE_string(name) \
310 namespace FLAG__namespace_do_not_use_directly_use_DECLARE_string_instead { \
311 extern GOOGLE_GLOG_DLL_DECL std::string FLAGS_##name; \
313 using FLAG__namespace_do_not_use_directly_use_DECLARE_string_instead::FLAGS_##name
316 // Set whether log messages go to stderr instead of logfiles
317 DECLARE_bool(logtostderr);
319 // Set whether log messages go to stderr in addition to logfiles.
320 DECLARE_bool(alsologtostderr);
322 // Log messages at a level >= this flag are automatically sent to
323 // stderr in addition to log files.
324 DECLARE_int32(stderrthreshold);
326 // Set whether the log prefix should be prepended to each line of output.
327 DECLARE_bool(log_prefix);
329 // Log messages at a level <= this flag are buffered.
330 // Log messages at a higher level are flushed immediately.
331 DECLARE_int32(logbuflevel);
333 // Sets the maximum number of seconds which logs may be buffered for.
334 DECLARE_int32(logbufsecs);
336 // Log suppression level: messages logged at a lower level than this
338 DECLARE_int32(minloglevel);
340 // If specified, logfiles are written into this directory instead of the
341 // default logging directory.
342 DECLARE_string(log_dir);
344 // Sets the path of the directory into which to put additional links
346 DECLARE_string(log_link);
348 DECLARE_int32(v); // in vlog_is_on.cc
350 // Sets the maximum log file size (in MB).
351 DECLARE_int32(max_log_size);
353 // Sets whether to avoid logging to the disk if the disk is full.
354 DECLARE_bool(stop_logging_if_full_disk);
356 #ifdef MUST_UNDEF_GFLAGS_DECLARE_MACROS
357 #undef MUST_UNDEF_GFLAGS_DECLARE_MACROS
358 #undef DECLARE_VARIABLE
361 #undef DECLARE_string
364 // Log messages below the GOOGLE_STRIP_LOG level will be compiled away for
365 // security reasons. See LOG(severtiy) below.
367 // A few definitions of macros that don't generate much code. Since
368 // LOG(INFO) and its ilk are used all over our code, it's
369 // better to have compact code for these operations.
371 #if GOOGLE_STRIP_LOG == 0
372 #define COMPACT_GOOGLE_LOG_INFO google::LogMessage( \
374 #define LOG_TO_STRING_INFO(message) google::LogMessage( \
375 __FILE__, __LINE__, google::GLOG_INFO, message)
377 #define COMPACT_GOOGLE_LOG_INFO google::NullStream()
378 #define LOG_TO_STRING_INFO(message) google::NullStream()
381 #if GOOGLE_STRIP_LOG <= 1
382 #define COMPACT_GOOGLE_LOG_WARNING google::LogMessage( \
383 __FILE__, __LINE__, google::GLOG_WARNING)
384 #define LOG_TO_STRING_WARNING(message) google::LogMessage( \
385 __FILE__, __LINE__, google::GLOG_WARNING, message)
387 #define COMPACT_GOOGLE_LOG_WARNING google::NullStream()
388 #define LOG_TO_STRING_WARNING(message) google::NullStream()
391 #if GOOGLE_STRIP_LOG <= 2
392 #define COMPACT_GOOGLE_LOG_ERROR google::LogMessage( \
393 __FILE__, __LINE__, google::GLOG_ERROR)
394 #define LOG_TO_STRING_ERROR(message) google::LogMessage( \
395 __FILE__, __LINE__, google::GLOG_ERROR, message)
397 #define COMPACT_GOOGLE_LOG_ERROR google::NullStream()
398 #define LOG_TO_STRING_ERROR(message) google::NullStream()
401 #if GOOGLE_STRIP_LOG <= 3
402 #define COMPACT_GOOGLE_LOG_FATAL google::LogMessageFatal( \
404 #define LOG_TO_STRING_FATAL(message) google::LogMessage( \
405 __FILE__, __LINE__, google::GLOG_FATAL, message)
407 #define COMPACT_GOOGLE_LOG_FATAL google::NullStreamFatal()
408 #define LOG_TO_STRING_FATAL(message) google::NullStreamFatal()
411 // For DFATAL, we want to use LogMessage (as opposed to
412 // LogMessageFatal), to be consistent with the original behavior.
414 #define COMPACT_GOOGLE_LOG_DFATAL COMPACT_GOOGLE_LOG_ERROR
415 #elif GOOGLE_STRIP_LOG <= 3
416 #define COMPACT_GOOGLE_LOG_DFATAL google::LogMessage( \
417 __FILE__, __LINE__, google::GLOG_FATAL)
419 #define COMPACT_GOOGLE_LOG_DFATAL google::NullStreamFatal()
422 #define GOOGLE_LOG_INFO(counter) google::LogMessage(__FILE__, __LINE__, google::GLOG_INFO, counter, &google::LogMessage::SendToLog)
423 #define SYSLOG_INFO(counter) \
424 google::LogMessage(__FILE__, __LINE__, google::GLOG_INFO, counter, \
425 &google::LogMessage::SendToSyslogAndLog)
426 #define GOOGLE_LOG_WARNING(counter) \
427 google::LogMessage(__FILE__, __LINE__, google::GLOG_WARNING, counter, \
428 &google::LogMessage::SendToLog)
429 #define SYSLOG_WARNING(counter) \
430 google::LogMessage(__FILE__, __LINE__, google::GLOG_WARNING, counter, \
431 &google::LogMessage::SendToSyslogAndLog)
432 #define GOOGLE_LOG_ERROR(counter) \
433 google::LogMessage(__FILE__, __LINE__, google::GLOG_ERROR, counter, \
434 &google::LogMessage::SendToLog)
435 #define SYSLOG_ERROR(counter) \
436 google::LogMessage(__FILE__, __LINE__, google::GLOG_ERROR, counter, \
437 &google::LogMessage::SendToSyslogAndLog)
438 #define GOOGLE_LOG_FATAL(counter) \
439 google::LogMessage(__FILE__, __LINE__, google::GLOG_FATAL, counter, \
440 &google::LogMessage::SendToLog)
441 #define SYSLOG_FATAL(counter) \
442 google::LogMessage(__FILE__, __LINE__, google::GLOG_FATAL, counter, \
443 &google::LogMessage::SendToSyslogAndLog)
444 #define GOOGLE_LOG_DFATAL(counter) \
445 google::LogMessage(__FILE__, __LINE__, google::DFATAL_LEVEL, counter, \
446 &google::LogMessage::SendToLog)
447 #define SYSLOG_DFATAL(counter) \
448 google::LogMessage(__FILE__, __LINE__, google::DFATAL_LEVEL, counter, \
449 &google::LogMessage::SendToSyslogAndLog)
451 #if defined(WIN32) || defined(_WIN32) || defined(__WIN32__) || defined(__CYGWIN__) || defined(__CYGWIN32__)
452 // A very useful logging macro to log windows errors:
453 #define LOG_SYSRESULT(result) \
454 if (FAILED(result)) { \
455 LPTSTR message = NULL; \
456 LPTSTR msg = reinterpret_cast<LPTSTR>(&message); \
457 DWORD message_length = FormatMessage(FORMAT_MESSAGE_ALLOCATE_BUFFER | \
458 FORMAT_MESSAGE_FROM_SYSTEM, \
459 0, result, 0, msg, 100, NULL); \
460 if (message_length > 0) { \
461 google::LogMessage(__FILE__, __LINE__, google::GLOG_ERROR, 0, \
462 &google::LogMessage::SendToLog).stream() << message; \
463 LocalFree(message); \
468 // We use the preprocessor's merging operator, "##", so that, e.g.,
469 // LOG(INFO) becomes the token GOOGLE_LOG_INFO. There's some funny
470 // subtle difference between ostream member streaming functions (e.g.,
471 // ostream::operator<<(int) and ostream non-member streaming functions
472 // (e.g., ::operator<<(ostream&, string&): it turns out that it's
473 // impossible to stream something like a string directly to an unnamed
474 // ostream. We employ a neat hack by calling the stream() member
475 // function of LogMessage which seems to avoid the problem.
476 #define LOG(severity) COMPACT_GOOGLE_LOG_ ## severity.stream()
477 #define SYSLOG(severity) SYSLOG_ ## severity(0).stream()
481 // They need the definitions of integer types.
482 #include "glog/log_severity.h"
483 #include "glog/vlog_is_on.h"
485 // Initialize google's logging library. You will see the program name
486 // specified by argv0 in log outputs.
487 GOOGLE_GLOG_DLL_DECL void InitGoogleLogging(const char* argv0);
489 // Shutdown google's logging library.
490 GOOGLE_GLOG_DLL_DECL void ShutdownGoogleLogging();
492 // Install a function which will be called after LOG(FATAL).
493 GOOGLE_GLOG_DLL_DECL void InstallFailureFunction(void (*fail_func)());
495 class LogSink; // defined below
497 // If a non-NULL sink pointer is given, we push this message to that sink.
498 // For LOG_TO_SINK we then do normal LOG(severity) logging as well.
499 // This is useful for capturing messages and passing/storing them
500 // somewhere more specific than the global log of the process.
503 // LogSeverity severity;
504 // The cast is to disambiguate NULL arguments.
505 #define LOG_TO_SINK(sink, severity) \
506 google::LogMessage( \
507 __FILE__, __LINE__, \
508 google::GLOG_ ## severity, \
509 static_cast<google::LogSink*>(sink), true).stream()
510 #define LOG_TO_SINK_BUT_NOT_TO_LOGFILE(sink, severity) \
511 google::LogMessage( \
512 __FILE__, __LINE__, \
513 google::GLOG_ ## severity, \
514 static_cast<google::LogSink*>(sink), false).stream()
516 // If a non-NULL string pointer is given, we write this message to that string.
517 // We then do normal LOG(severity) logging as well.
518 // This is useful for capturing messages and storing them somewhere more
519 // specific than the global log of the process.
522 // LogSeverity severity;
523 // The cast is to disambiguate NULL arguments.
524 // NOTE: LOG(severity) expands to LogMessage().stream() for the specified
526 #define LOG_TO_STRING(severity, message) \
527 LOG_TO_STRING_##severity(static_cast<string*>(message)).stream()
529 // If a non-NULL pointer is given, we push the message onto the end
530 // of a vector of strings; otherwise, we report it with LOG(severity).
531 // This is handy for capturing messages and perhaps passing them back
532 // to the caller, rather than reporting them immediately.
534 // LogSeverity severity;
535 // vector<string> *outvec;
536 // The cast is to disambiguate NULL arguments.
537 #define LOG_STRING(severity, outvec) \
538 LOG_TO_STRING_##severity(static_cast<vector<string>*>(outvec)).stream()
540 #define LOG_IF(severity, condition) \
541 !(condition) ? (void) 0 : google::LogMessageVoidify() & LOG(severity)
542 #define SYSLOG_IF(severity, condition) \
543 !(condition) ? (void) 0 : google::LogMessageVoidify() & SYSLOG(severity)
545 #define LOG_ASSERT(condition) \
546 LOG_IF(FATAL, !(condition)) << "Assert failed: " #condition
547 #define SYSLOG_ASSERT(condition) \
548 SYSLOG_IF(FATAL, !(condition)) << "Assert failed: " #condition
550 // CHECK dies with a fatal error if condition is not true. It is *not*
551 // controlled by NDEBUG, so the check will be executed regardless of
552 // compilation mode. Therefore, it is safe to do things like:
553 // CHECK(fp->Write(x) == 4)
554 #define CHECK(condition) \
555 LOG_IF(FATAL, GOOGLE_PREDICT_BRANCH_NOT_TAKEN(!(condition))) \
556 << "Check failed: " #condition " "
558 // A container for a string pointer which can be evaluated to a bool -
559 // true iff the pointer is NULL.
560 struct CheckOpString {
561 CheckOpString(std::string* str) : str_(str) { }
562 // No destructor: if str_ is non-NULL, we're about to LOG(FATAL),
563 // so there's no point in cleaning up str_.
564 operator bool() const {
565 return GOOGLE_PREDICT_BRANCH_NOT_TAKEN(str_ != NULL);
570 // Function is overloaded for integral types to allow static const
571 // integrals declared in classes and not defined to be used as arguments to
572 // CHECK* macros. It's not encouraged though.
574 inline const T& GetReferenceableValue(const T& t) { return t; }
575 inline char GetReferenceableValue(char t) { return t; }
576 inline unsigned char GetReferenceableValue(unsigned char t) { return t; }
577 inline signed char GetReferenceableValue(signed char t) { return t; }
578 inline short GetReferenceableValue(short t) { return t; }
579 inline unsigned short GetReferenceableValue(unsigned short t) { return t; }
580 inline int GetReferenceableValue(int t) { return t; }
581 inline unsigned int GetReferenceableValue(unsigned int t) { return t; }
582 inline long GetReferenceableValue(long t) { return t; }
583 inline unsigned long GetReferenceableValue(unsigned long t) { return t; }
584 inline long long GetReferenceableValue(long long t) { return t; }
585 inline unsigned long long GetReferenceableValue(unsigned long long t) {
589 // This is a dummy class to define the following operator.
590 struct DummyClassToDefineOperator {};
594 // Define global operator<< to declare using ::operator<<.
595 // This declaration will allow use to use CHECK macros for user
596 // defined classes which have operator<< (e.g., stl_logging.h).
597 inline std::ostream& operator<<(
598 std::ostream& out, const google::DummyClassToDefineOperator&) {
604 // Build the error message string.
605 template<class t1, class t2>
606 std::string* MakeCheckOpString(const t1& v1, const t2& v2, const char* names) {
607 // It means that we cannot use stl_logging if compiler doesn't
608 // support using expression for operator.
609 // TODO(hamaji): Figure out a way to fix.
614 ss << names << " (" << v1 << " vs. " << v2 << ")";
615 return new std::string(ss.str(), ss.pcount());
618 // Helper functions for CHECK_OP macro.
619 // The (int, int) specialization works around the issue that the compiler
620 // will not instantiate the template version of the function on values of
621 // unnamed enum type - see comment below.
622 #define DEFINE_CHECK_OP_IMPL(name, op) \
623 template <class t1, class t2> \
624 inline std::string* Check##name##Impl(const t1& v1, const t2& v2, \
625 const char* names) { \
626 if (v1 op v2) return NULL; \
627 else return MakeCheckOpString(v1, v2, names); \
629 inline std::string* Check##name##Impl(int v1, int v2, const char* names) { \
630 return Check##name##Impl<int, int>(v1, v2, names); \
633 // Use _EQ, _NE, _LE, etc. in case the file including base/logging.h
634 // provides its own #defines for the simpler names EQ, NE, LE, etc.
635 // This happens if, for example, those are used as token names in a
637 DEFINE_CHECK_OP_IMPL(_EQ, ==)
638 DEFINE_CHECK_OP_IMPL(_NE, !=)
639 DEFINE_CHECK_OP_IMPL(_LE, <=)
640 DEFINE_CHECK_OP_IMPL(_LT, < )
641 DEFINE_CHECK_OP_IMPL(_GE, >=)
642 DEFINE_CHECK_OP_IMPL(_GT, > )
643 #undef DEFINE_CHECK_OP_IMPL
645 // Helper macro for binary operators.
646 // Don't use this macro directly in your code, use CHECK_EQ et al below.
648 #if defined(STATIC_ANALYSIS)
649 // Only for static analysis tool to know that it is equivalent to assert
650 #define CHECK_OP_LOG(name, op, val1, val2, log) CHECK((val1) op (val2))
651 #elif !defined(NDEBUG)
652 // In debug mode, avoid constructing CheckOpStrings if possible,
653 // to reduce the overhead of CHECK statments by 2x.
654 // Real DCHECK-heavy tests have seen 1.5x speedups.
656 // The meaning of "string" might be different between now and
657 // when this macro gets invoked (e.g., if someone is experimenting
658 // with other string implementations that get defined after this
659 // file is included). Save the current meaning now and use it
661 typedef std::string _Check_string;
662 #define CHECK_OP_LOG(name, op, val1, val2, log) \
663 while (google::_Check_string* _result = \
664 google::Check##name##Impl( \
665 google::GetReferenceableValue(val1), \
666 google::GetReferenceableValue(val2), \
667 #val1 " " #op " " #val2)) \
668 log(__FILE__, __LINE__, \
669 google::CheckOpString(_result)).stream()
671 // In optimized mode, use CheckOpString to hint to compiler that
672 // the while condition is unlikely.
673 #define CHECK_OP_LOG(name, op, val1, val2, log) \
674 while (google::CheckOpString _result = \
675 google::Check##name##Impl( \
676 google::GetReferenceableValue(val1), \
677 google::GetReferenceableValue(val2), \
678 #val1 " " #op " " #val2)) \
679 log(__FILE__, __LINE__, _result).stream()
680 #endif // STATIC_ANALYSIS, !NDEBUG
682 #if GOOGLE_STRIP_LOG <= 3
683 #define CHECK_OP(name, op, val1, val2) \
684 CHECK_OP_LOG(name, op, val1, val2, google::LogMessageFatal)
686 #define CHECK_OP(name, op, val1, val2) \
687 CHECK_OP_LOG(name, op, val1, val2, google::NullStreamFatal)
688 #endif // STRIP_LOG <= 3
690 // Equality/Inequality checks - compare two values, and log a FATAL message
691 // including the two values when the result is not as expected. The values
692 // must have operator<<(ostream, ...) defined.
694 // You may append to the error message like so:
695 // CHECK_NE(1, 2) << ": The world must be ending!";
697 // We are very careful to ensure that each argument is evaluated exactly
698 // once, and that anything which is legal to pass as a function argument is
699 // legal here. In particular, the arguments may be temporary expressions
700 // which will end up being destroyed at the end of the apparent statement,
702 // CHECK_EQ(string("abc")[1], 'b');
704 // WARNING: These don't compile correctly if one of the arguments is a pointer
705 // and the other is NULL. To work around this, simply static_cast NULL to the
706 // type of the desired pointer.
708 #define CHECK_EQ(val1, val2) CHECK_OP(_EQ, ==, val1, val2)
709 #define CHECK_NE(val1, val2) CHECK_OP(_NE, !=, val1, val2)
710 #define CHECK_LE(val1, val2) CHECK_OP(_LE, <=, val1, val2)
711 #define CHECK_LT(val1, val2) CHECK_OP(_LT, < , val1, val2)
712 #define CHECK_GE(val1, val2) CHECK_OP(_GE, >=, val1, val2)
713 #define CHECK_GT(val1, val2) CHECK_OP(_GT, > , val1, val2)
715 // Check that the input is non NULL. This very useful in constructor
716 // initializer lists.
718 #define CHECK_NOTNULL(val) \
719 google::CheckNotNull(__FILE__, __LINE__, "'" #val "' Must be non NULL", (val))
721 // Helper functions for string comparisons.
722 // To avoid bloat, the definitions are in logging.cc.
723 #define DECLARE_CHECK_STROP_IMPL(func, expected) \
724 GOOGLE_GLOG_DLL_DECL std::string* Check##func##expected##Impl( \
725 const char* s1, const char* s2, const char* names);
726 DECLARE_CHECK_STROP_IMPL(strcmp, true)
727 DECLARE_CHECK_STROP_IMPL(strcmp, false)
728 DECLARE_CHECK_STROP_IMPL(strcasecmp, true)
729 DECLARE_CHECK_STROP_IMPL(strcasecmp, false)
730 #undef DECLARE_CHECK_STROP_IMPL
732 // Helper macro for string comparisons.
733 // Don't use this macro directly in your code, use CHECK_STREQ et al below.
734 #define CHECK_STROP(func, op, expected, s1, s2) \
735 while (google::CheckOpString _result = \
736 google::Check##func##expected##Impl((s1), (s2), \
737 #s1 " " #op " " #s2)) \
738 LOG(FATAL) << *_result.str_
741 // String (char*) equality/inequality checks.
742 // CASE versions are case-insensitive.
744 // Note that "s1" and "s2" may be temporary strings which are destroyed
745 // by the compiler at the end of the current "full expression"
746 // (e.g. CHECK_STREQ(Foo().c_str(), Bar().c_str())).
748 #define CHECK_STREQ(s1, s2) CHECK_STROP(strcmp, ==, true, s1, s2)
749 #define CHECK_STRNE(s1, s2) CHECK_STROP(strcmp, !=, false, s1, s2)
750 #define CHECK_STRCASEEQ(s1, s2) CHECK_STROP(strcasecmp, ==, true, s1, s2)
751 #define CHECK_STRCASENE(s1, s2) CHECK_STROP(strcasecmp, !=, false, s1, s2)
753 #define CHECK_INDEX(I,A) CHECK(I < (sizeof(A)/sizeof(A[0])))
754 #define CHECK_BOUND(B,A) CHECK(B <= (sizeof(A)/sizeof(A[0])))
756 #define CHECK_DOUBLE_EQ(val1, val2) \
758 CHECK_LE((val1), (val2)+0.000000000000001L); \
759 CHECK_GE((val1), (val2)-0.000000000000001L); \
762 #define CHECK_NEAR(val1, val2, margin) \
764 CHECK_LE((val1), (val2)+(margin)); \
765 CHECK_GE((val1), (val2)-(margin)); \
768 // perror()..googly style!
770 // PLOG() and PLOG_IF() and PCHECK() behave exactly like their LOG* and
771 // CHECK equivalents with the addition that they postpend a description
772 // of the current state of errno to their output lines.
774 #define PLOG(severity) GOOGLE_PLOG(severity, 0).stream()
776 #define GOOGLE_PLOG(severity, counter) \
777 google::ErrnoLogMessage( \
778 __FILE__, __LINE__, google::GLOG_ ## severity, counter, \
779 &google::LogMessage::SendToLog)
781 #define PLOG_IF(severity, condition) \
782 !(condition) ? (void) 0 : google::LogMessageVoidify() & PLOG(severity)
784 // A CHECK() macro that postpends errno if the condition is false. E.g.
786 // if (poll(fds, nfds, timeout) == -1) { PCHECK(errno == EINTR); ... }
787 #define PCHECK(condition) \
788 PLOG_IF(FATAL, GOOGLE_PREDICT_BRANCH_NOT_TAKEN(!(condition))) \
789 << "Check failed: " #condition " "
791 // A CHECK() macro that lets you assert the success of a function that
792 // returns -1 and sets errno in case of an error. E.g.
794 // CHECK_ERR(mkdir(path, 0700));
798 // int fd = open(filename, flags); CHECK_ERR(fd) << ": open " << filename;
799 #define CHECK_ERR(invocation) \
800 PLOG_IF(FATAL, GOOGLE_PREDICT_BRANCH_NOT_TAKEN((invocation) == -1)) \
803 // Use macro expansion to create, for each use of LOG_EVERY_N(), static
804 // variables with the __LINE__ expansion as part of the variable name.
805 #define LOG_EVERY_N_VARNAME(base, line) LOG_EVERY_N_VARNAME_CONCAT(base, line)
806 #define LOG_EVERY_N_VARNAME_CONCAT(base, line) base ## line
808 #define LOG_OCCURRENCES LOG_EVERY_N_VARNAME(occurrences_, __LINE__)
809 #define LOG_OCCURRENCES_MOD_N LOG_EVERY_N_VARNAME(occurrences_mod_n_, __LINE__)
811 #define SOME_KIND_OF_LOG_EVERY_N(severity, n, what_to_do) \
812 static int LOG_OCCURRENCES = 0, LOG_OCCURRENCES_MOD_N = 0; \
814 if (++LOG_OCCURRENCES_MOD_N > n) LOG_OCCURRENCES_MOD_N -= n; \
815 if (LOG_OCCURRENCES_MOD_N == 1) \
816 google::LogMessage( \
817 __FILE__, __LINE__, google::GLOG_ ## severity, LOG_OCCURRENCES, \
818 &what_to_do).stream()
820 #define SOME_KIND_OF_LOG_IF_EVERY_N(severity, condition, n, what_to_do) \
821 static int LOG_OCCURRENCES = 0, LOG_OCCURRENCES_MOD_N = 0; \
824 ((LOG_OCCURRENCES_MOD_N=(LOG_OCCURRENCES_MOD_N + 1) % n) == (1 % n))) \
825 google::LogMessage( \
826 __FILE__, __LINE__, google::GLOG_ ## severity, LOG_OCCURRENCES, \
827 &what_to_do).stream()
829 #define SOME_KIND_OF_PLOG_EVERY_N(severity, n, what_to_do) \
830 static int LOG_OCCURRENCES = 0, LOG_OCCURRENCES_MOD_N = 0; \
832 if (++LOG_OCCURRENCES_MOD_N > n) LOG_OCCURRENCES_MOD_N -= n; \
833 if (LOG_OCCURRENCES_MOD_N == 1) \
834 google::ErrnoLogMessage( \
835 __FILE__, __LINE__, google::GLOG_ ## severity, LOG_OCCURRENCES, \
836 &what_to_do).stream()
838 #define SOME_KIND_OF_LOG_FIRST_N(severity, n, what_to_do) \
839 static int LOG_OCCURRENCES = 0; \
840 if (LOG_OCCURRENCES <= n) \
842 if (LOG_OCCURRENCES <= n) \
843 google::LogMessage( \
844 __FILE__, __LINE__, google::GLOG_ ## severity, LOG_OCCURRENCES, \
845 &what_to_do).stream()
847 namespace glog_internal_namespace_ {
849 struct CompileAssert {
852 } // namespace glog_internal_namespace_
854 #define GOOGLE_GLOG_COMPILE_ASSERT(expr, msg) \
855 typedef google::glog_internal_namespace_::CompileAssert<(bool(expr))> msg[bool(expr) ? 1 : -1]
857 #define LOG_EVERY_N(severity, n) \
858 GOOGLE_GLOG_COMPILE_ASSERT(google::GLOG_ ## severity < \
859 google::NUM_SEVERITIES, \
860 INVALID_REQUESTED_LOG_SEVERITY); \
861 SOME_KIND_OF_LOG_EVERY_N(severity, (n), google::LogMessage::SendToLog)
863 #define SYSLOG_EVERY_N(severity, n) \
864 SOME_KIND_OF_LOG_EVERY_N(severity, (n), google::LogMessage::SendToSyslogAndLog)
866 #define PLOG_EVERY_N(severity, n) \
867 SOME_KIND_OF_PLOG_EVERY_N(severity, (n), google::LogMessage::SendToLog)
869 #define LOG_FIRST_N(severity, n) \
870 SOME_KIND_OF_LOG_FIRST_N(severity, (n), google::LogMessage::SendToLog)
872 #define LOG_IF_EVERY_N(severity, condition, n) \
873 SOME_KIND_OF_LOG_IF_EVERY_N(severity, (condition), (n), google::LogMessage::SendToLog)
875 // We want the special COUNTER value available for LOG_EVERY_X()'ed messages
876 enum PRIVATE_Counter {COUNTER};
878 #ifdef GLOG_NO_ABBREVIATED_SEVERITIES
879 // wingdi.h defines ERROR to be 0. When we call LOG(ERROR), it gets
880 // substituted with 0, and it expands to COMPACT_GOOGLE_LOG_0. To allow us
881 // to keep using this syntax, we define this macro to do the same thing
882 // as COMPACT_GOOGLE_LOG_ERROR.
883 #define COMPACT_GOOGLE_LOG_0 COMPACT_GOOGLE_LOG_ERROR
884 #define SYSLOG_0 SYSLOG_ERROR
885 #define LOG_TO_STRING_0 LOG_TO_STRING_ERROR
886 // Needed for LOG_IS_ON(ERROR).
887 const LogSeverity GLOG_0 = GLOG_ERROR;
889 // Users may include windows.h after logging.h without
890 // GLOG_NO_ABBREVIATED_SEVERITIES nor WIN32_LEAN_AND_MEAN.
891 // For this case, we cannot detect if ERROR is defined before users
892 // actually use ERROR. Let's make an undefined symbol to warn users.
893 # define GLOG_ERROR_MSG ERROR_macro_is_defined_Define_GLOG_NO_ABBREVIATED_SEVERITIES_before_including_logging_h_See_the_document_for_detail
894 # define COMPACT_GOOGLE_LOG_0 GLOG_ERROR_MSG
895 # define SYSLOG_0 GLOG_ERROR_MSG
896 # define LOG_TO_STRING_0 GLOG_ERROR_MSG
897 # define GLOG_0 GLOG_ERROR_MSG
900 // Plus some debug-logging macros that get compiled to nothing for production
904 #define DLOG(severity) LOG(severity)
905 #define DVLOG(verboselevel) VLOG(verboselevel)
906 #define DLOG_IF(severity, condition) LOG_IF(severity, condition)
907 #define DLOG_EVERY_N(severity, n) LOG_EVERY_N(severity, n)
908 #define DLOG_IF_EVERY_N(severity, condition, n) \
909 LOG_IF_EVERY_N(severity, condition, n)
910 #define DLOG_ASSERT(condition) LOG_ASSERT(condition)
912 // debug-only checking. not executed in NDEBUG mode.
913 #define DCHECK(condition) CHECK(condition)
914 #define DCHECK_EQ(val1, val2) CHECK_EQ(val1, val2)
915 #define DCHECK_NE(val1, val2) CHECK_NE(val1, val2)
916 #define DCHECK_LE(val1, val2) CHECK_LE(val1, val2)
917 #define DCHECK_LT(val1, val2) CHECK_LT(val1, val2)
918 #define DCHECK_GE(val1, val2) CHECK_GE(val1, val2)
919 #define DCHECK_GT(val1, val2) CHECK_GT(val1, val2)
920 #define DCHECK_NOTNULL(val) CHECK_NOTNULL(val)
921 #define DCHECK_STREQ(str1, str2) CHECK_STREQ(str1, str2)
922 #define DCHECK_STRCASEEQ(str1, str2) CHECK_STRCASEEQ(str1, str2)
923 #define DCHECK_STRNE(str1, str2) CHECK_STRNE(str1, str2)
924 #define DCHECK_STRCASENE(str1, str2) CHECK_STRCASENE(str1, str2)
928 #define DLOG(severity) \
929 true ? (void) 0 : google::LogMessageVoidify() & LOG(severity)
931 #define DVLOG(verboselevel) \
932 (true || !VLOG_IS_ON(verboselevel)) ?\
933 (void) 0 : google::LogMessageVoidify() & LOG(INFO)
935 #define DLOG_IF(severity, condition) \
936 (true || !(condition)) ? (void) 0 : google::LogMessageVoidify() & LOG(severity)
938 #define DLOG_EVERY_N(severity, n) \
939 true ? (void) 0 : google::LogMessageVoidify() & LOG(severity)
941 #define DLOG_IF_EVERY_N(severity, condition, n) \
942 (true || !(condition))? (void) 0 : google::LogMessageVoidify() & LOG(severity)
944 #define DLOG_ASSERT(condition) \
945 true ? (void) 0 : LOG_ASSERT(condition)
947 #define DCHECK(condition) \
951 #define DCHECK_EQ(val1, val2) \
955 #define DCHECK_NE(val1, val2) \
959 #define DCHECK_LE(val1, val2) \
963 #define DCHECK_LT(val1, val2) \
967 #define DCHECK_GE(val1, val2) \
971 #define DCHECK_GT(val1, val2) \
975 #define DCHECK_NOTNULL(val) (val)
977 #define DCHECK_STREQ(str1, str2) \
979 CHECK_STREQ(str1, str2)
981 #define DCHECK_STRCASEEQ(str1, str2) \
983 CHECK_STRCASEEQ(str1, str2)
985 #define DCHECK_STRNE(str1, str2) \
987 CHECK_STRNE(str1, str2)
989 #define DCHECK_STRCASENE(str1, str2) \
991 CHECK_STRCASENE(str1, str2)
996 // Log only in verbose mode.
998 #define VLOG(verboselevel) LOG_IF(INFO, VLOG_IS_ON(verboselevel))
1000 #define VLOG_IF(verboselevel, condition) \
1001 LOG_IF(INFO, (condition) && VLOG_IS_ON(verboselevel))
1003 #define VLOG_EVERY_N(verboselevel, n) \
1004 LOG_IF_EVERY_N(INFO, VLOG_IS_ON(verboselevel), n)
1006 #define VLOG_IF_EVERY_N(verboselevel, condition, n) \
1007 LOG_IF_EVERY_N(INFO, (condition) && VLOG_IS_ON(verboselevel), n)
1010 // This class more or less represents a particular log message. You
1011 // create an instance of LogMessage and then stream stuff to it.
1012 // When you finish streaming to it, ~LogMessage is called and the
1013 // full message gets streamed to the appropriate destination.
1015 // You shouldn't actually use LogMessage's constructor to log things,
1016 // though. You should use the LOG() macro (and variants thereof)
1018 class GOOGLE_GLOG_DLL_DECL LogMessage {
1021 // Passing kNoLogPrefix for the line number disables the
1022 // log-message prefix. Useful for using the LogMessage
1023 // infrastructure as a printing utility. See also the --log_prefix
1024 // flag for controlling the log-message prefix on an
1025 // application-wide basis.
1029 // LogStream inherit from non-DLL-exported class (std::ostrstream)
1030 // and VC++ produces a warning for this situation.
1031 // However, MSDN says "C4275 can be ignored in Microsoft Visual C++
1032 // 2005 if you are deriving from a type in the Standard C++ Library"
1033 // http://msdn.microsoft.com/en-us/library/3tdb471s(VS.80).aspx
1034 // Let's just ignore the warning.
1036 # pragma warning(disable: 4275)
1038 class GOOGLE_GLOG_DLL_DECL LogStream : public std::ostrstream {
1040 # pragma warning(default: 4275)
1043 LogStream(char *buf, int len, int ctr_in)
1044 : ostrstream(buf, len),
1049 int ctr() const { return ctr_; }
1050 void set_ctr(int ctr_in) { ctr_ = ctr_in; }
1051 LogStream* self() const { return self_; }
1054 int ctr_; // Counter hack (for the LOG_EVERY_X() macro)
1055 LogStream *self_; // Consistency check hack
1059 // icc 8 requires this typedef to avoid an internal compiler error.
1060 typedef void (LogMessage::*SendMethod)();
1062 LogMessage(const char* file, int line, LogSeverity severity, int ctr,
1063 SendMethod send_method);
1065 // Two special constructors that generate reduced amounts of code at
1066 // LOG call sites for common cases.
1068 // Used for LOG(INFO): Implied are:
1069 // severity = INFO, ctr = 0, send_method = &LogMessage::SendToLog.
1071 // Using this constructor instead of the more complex constructor above
1072 // saves 19 bytes per call site.
1073 LogMessage(const char* file, int line);
1075 // Used for LOG(severity) where severity != INFO. Implied
1076 // are: ctr = 0, send_method = &LogMessage::SendToLog
1078 // Using this constructor instead of the more complex constructor above
1079 // saves 17 bytes per call site.
1080 LogMessage(const char* file, int line, LogSeverity severity);
1082 // Constructor to log this message to a specified sink (if not NULL).
1083 // Implied are: ctr = 0, send_method = &LogMessage::SendToSinkAndLog if
1084 // also_send_to_log is true, send_method = &LogMessage::SendToSink otherwise.
1085 LogMessage(const char* file, int line, LogSeverity severity, LogSink* sink,
1086 bool also_send_to_log);
1088 // Constructor where we also give a vector<string> pointer
1089 // for storing the messages (if the pointer is not NULL).
1090 // Implied are: ctr = 0, send_method = &LogMessage::SaveOrSendToLog.
1091 LogMessage(const char* file, int line, LogSeverity severity,
1092 std::vector<std::string>* outvec);
1094 // Constructor where we also give a string pointer for storing the
1095 // message (if the pointer is not NULL). Implied are: ctr = 0,
1096 // send_method = &LogMessage::WriteToStringAndLog.
1097 LogMessage(const char* file, int line, LogSeverity severity,
1098 std::string* message);
1100 // A special constructor used for check failures
1101 LogMessage(const char* file, int line, const CheckOpString& result);
1105 // Flush a buffered message to the sink set in the constructor. Always
1106 // called by the destructor, it may also be called from elsewhere if
1107 // needed. Only the first call is actioned; any later ones are ignored.
1110 // An arbitrary limit on the length of a single log message. This
1111 // is so that streaming can be done more efficiently.
1112 static const size_t kMaxLogMessageLen;
1114 // Theses should not be called directly outside of logging.*,
1115 // only passed as SendMethod arguments to other LogMessage methods:
1116 void SendToLog(); // Actually dispatch to the logs
1117 void SendToSyslogAndLog(); // Actually dispatch to syslog and the logs
1119 // Call abort() or similar to perform LOG(FATAL) crash.
1120 static void Fail() ;
1122 std::ostream& stream() { return *(data_->stream_); }
1124 int preserved_errno() const { return data_->preserved_errno_; }
1126 // Must be called without the log_mutex held. (L < log_mutex)
1127 static int64 num_messages(int severity);
1130 // Fully internal SendMethod cases:
1131 void SendToSinkAndLog(); // Send to sink if provided and dispatch to the logs
1132 void SendToSink(); // Send to sink if provided, do nothing otherwise.
1134 // Write to string if provided and dispatch to the logs.
1135 void WriteToStringAndLog();
1137 void SaveOrSendToLog(); // Save to stringvec if provided, else to logs
1139 void Init(const char* file, int line, LogSeverity severity,
1140 void (LogMessage::*send_method)());
1142 // Used to fill in crash information during LOG(FATAL) failures.
1143 void RecordCrashReason(glog_internal_namespace_::CrashReason* reason);
1145 // Counts of messages sent at each priority:
1146 static int64 num_messages_[NUM_SEVERITIES]; // under log_mutex
1148 // We keep the data in a separate struct so that each instance of
1149 // LogMessage uses less stack space.
1150 struct GOOGLE_GLOG_DLL_DECL LogMessageData {
1151 LogMessageData() {};
1153 int preserved_errno_; // preserved errno
1155 char* message_text_; // Complete message text (points to selected buffer)
1156 LogStream* stream_alloc_;
1158 char severity_; // What level is this LogMessage logged at?
1159 int line_; // line number where logging call is.
1160 void (LogMessage::*send_method_)(); // Call this in destructor to send
1161 union { // At most one of these is used: union to keep the size low.
1162 LogSink* sink_; // NULL or sink to send message to
1163 std::vector<std::string>* outvec_; // NULL or vector to push message onto
1164 std::string* message_; // NULL or string to write message into
1166 time_t timestamp_; // Time of creation of LogMessage
1167 struct ::tm tm_time_; // Time of creation of LogMessage
1168 size_t num_prefix_chars_; // # of chars of prefix in this message
1169 size_t num_chars_to_log_; // # of chars of msg to send to log
1170 size_t num_chars_to_syslog_; // # of chars of msg to send to syslog
1171 const char* basename_; // basename of file that called LOG
1172 const char* fullname_; // fullname of file that called LOG
1173 bool has_been_flushed_; // false => data has not been flushed
1174 bool first_fatal_; // true => this was first fatal msg
1178 LogMessageData(const LogMessageData&);
1179 void operator=(const LogMessageData&);
1182 static LogMessageData fatal_msg_data_exclusive_;
1183 static LogMessageData fatal_msg_data_shared_;
1185 LogMessageData* allocated_;
1186 LogMessageData* data_;
1188 friend class LogDestination;
1190 LogMessage(const LogMessage&);
1191 void operator=(const LogMessage&);
1194 // This class happens to be thread-hostile because all instances share
1195 // a single data buffer, but since it can only be created just before
1196 // the process dies, we don't worry so much.
1197 class GOOGLE_GLOG_DLL_DECL LogMessageFatal : public LogMessage {
1199 LogMessageFatal(const char* file, int line);
1200 LogMessageFatal(const char* file, int line, const CheckOpString& result);
1201 ~LogMessageFatal() ;
1204 // A non-macro interface to the log facility; (useful
1205 // when the logging level is not a compile-time constant).
1206 inline void LogAtLevel(int const severity, std::string const &msg) {
1207 LogMessage(__FILE__, __LINE__, severity).stream() << msg;
1210 // A macro alternative of LogAtLevel. New code may want to use this
1211 // version since there are two advantages: 1. this version outputs the
1212 // file name and the line number where this macro is put like other
1213 // LOG macros, 2. this macro can be used as C++ stream.
1214 #define LOG_AT_LEVEL(severity) google::LogMessage(__FILE__, __LINE__, severity).stream()
1216 // A small helper for CHECK_NOTNULL().
1217 template <typename T>
1218 T* CheckNotNull(const char *file, int line, const char *names, T* t) {
1220 LogMessageFatal(file, line, new std::string(names));
1225 // Allow folks to put a counter in the LOG_EVERY_X()'ed messages. This
1226 // only works if ostream is a LogStream. If the ostream is not a
1227 // LogStream you'll get an assert saying as much at runtime.
1228 GOOGLE_GLOG_DLL_DECL std::ostream& operator<<(std::ostream &os,
1229 const PRIVATE_Counter&);
1232 // Derived class for PLOG*() above.
1233 class GOOGLE_GLOG_DLL_DECL ErrnoLogMessage : public LogMessage {
1236 ErrnoLogMessage(const char* file, int line, LogSeverity severity, int ctr,
1237 void (LogMessage::*send_method)());
1239 // Postpends ": strerror(errno) [errno]".
1243 ErrnoLogMessage(const ErrnoLogMessage&);
1244 void operator=(const ErrnoLogMessage&);
1248 // This class is used to explicitly ignore values in the conditional
1249 // logging macros. This avoids compiler warnings like "value computed
1250 // is not used" and "statement has no effect".
1252 class GOOGLE_GLOG_DLL_DECL LogMessageVoidify {
1254 LogMessageVoidify() { }
1255 // This has to be an operator with a precedence lower than << but
1257 void operator&(std::ostream&) { }
1261 // Flushes all log files that contains messages that are at least of
1262 // the specified severity level. Thread-safe.
1263 GOOGLE_GLOG_DLL_DECL void FlushLogFiles(LogSeverity min_severity);
1265 // Flushes all log files that contains messages that are at least of
1266 // the specified severity level. Thread-hostile because it ignores
1267 // locking -- used for catastrophic failures.
1268 GOOGLE_GLOG_DLL_DECL void FlushLogFilesUnsafe(LogSeverity min_severity);
1271 // Set the destination to which a particular severity level of log
1272 // messages is sent. If base_filename is "", it means "don't log this
1273 // severity". Thread-safe.
1275 GOOGLE_GLOG_DLL_DECL void SetLogDestination(LogSeverity severity,
1276 const char* base_filename);
1279 // Set the basename of the symlink to the latest log file at a given
1280 // severity. If symlink_basename is empty, do not make a symlink. If
1281 // you don't call this function, the symlink basename is the
1282 // invocation name of the program. Thread-safe.
1284 GOOGLE_GLOG_DLL_DECL void SetLogSymlink(LogSeverity severity,
1285 const char* symlink_basename);
1288 // Used to send logs to some other kind of destination
1289 // Users should subclass LogSink and override send to do whatever they want.
1290 // Implementations must be thread-safe because a shared instance will
1291 // be called from whichever thread ran the LOG(XXX) line.
1292 class GOOGLE_GLOG_DLL_DECL LogSink {
1296 // Sink's logging logic (message_len is such as to exclude '\n' at the end).
1297 // This method can't use LOG() or CHECK() as logging system mutex(s) are held
1298 // during this call.
1299 virtual void send(LogSeverity severity, const char* full_filename,
1300 const char* base_filename, int line,
1301 const struct ::tm* tm_time,
1302 const char* message, size_t message_len) = 0;
1304 // Redefine this to implement waiting for
1305 // the sink's logging logic to complete.
1306 // It will be called after each send() returns,
1307 // but before that LogMessage exits or crashes.
1308 // By default this function does nothing.
1309 // Using this function one can implement complex logic for send()
1310 // that itself involves logging; and do all this w/o causing deadlocks and
1311 // inconsistent rearrangement of log messages.
1312 // E.g. if a LogSink has thread-specific actions, the send() method
1313 // can simply add the message to a queue and wake up another thread that
1314 // handles real logging while itself making some LOG() calls;
1315 // WaitTillSent() can be implemented to wait for that logic to complete.
1316 // See our unittest for an example.
1317 virtual void WaitTillSent();
1319 // Returns the normal text output of the log message.
1320 // Can be useful to implement send().
1321 static std::string ToString(LogSeverity severity, const char* file, int line,
1322 const struct ::tm* tm_time,
1323 const char* message, size_t message_len);
1326 // Add or remove a LogSink as a consumer of logging data. Thread-safe.
1327 GOOGLE_GLOG_DLL_DECL void AddLogSink(LogSink *destination);
1328 GOOGLE_GLOG_DLL_DECL void RemoveLogSink(LogSink *destination);
1331 // Specify an "extension" added to the filename specified via
1332 // SetLogDestination. This applies to all severity levels. It's
1333 // often used to append the port we're listening on to the logfile
1334 // name. Thread-safe.
1336 GOOGLE_GLOG_DLL_DECL void SetLogFilenameExtension(
1337 const char* filename_extension);
1340 // Make it so that all log messages of at least a particular severity
1341 // are logged to stderr (in addition to logging to the usual log
1342 // file(s)). Thread-safe.
1344 GOOGLE_GLOG_DLL_DECL void SetStderrLogging(LogSeverity min_severity);
1347 // Make it so that all log messages go only to stderr. Thread-safe.
1349 GOOGLE_GLOG_DLL_DECL void LogToStderr();
1352 // Make it so that all log messages of at least a particular severity are
1353 // logged via email to a list of addresses (in addition to logging to the
1354 // usual log file(s)). The list of addresses is just a string containing
1355 // the email addresses to send to (separated by spaces, say). Thread-safe.
1357 GOOGLE_GLOG_DLL_DECL void SetEmailLogging(LogSeverity min_severity,
1358 const char* addresses);
1360 // A simple function that sends email. dest is a commma-separated
1361 // list of addressess. Thread-safe.
1362 GOOGLE_GLOG_DLL_DECL bool SendEmail(const char *dest,
1363 const char *subject, const char *body);
1365 GOOGLE_GLOG_DLL_DECL const std::vector<std::string>& GetLoggingDirectories();
1367 // For tests only: Clear the internal [cached] list of logging directories to
1368 // force a refresh the next time GetLoggingDirectories is called.
1370 void TestOnly_ClearLoggingDirectoriesList();
1372 // Returns a set of existing temporary directories, which will be a
1373 // subset of the directories returned by GetLogginDirectories().
1375 GOOGLE_GLOG_DLL_DECL void GetExistingTempDirectories(
1376 std::vector<std::string>* list);
1378 // Print any fatal message again -- useful to call from signal handler
1379 // so that the last thing in the output is the fatal message.
1380 // Thread-hostile, but a race is unlikely.
1381 GOOGLE_GLOG_DLL_DECL void ReprintFatalMessage();
1383 // Truncate a log file that may be the append-only output of multiple
1384 // processes and hence can't simply be renamed/reopened (typically a
1385 // stdout/stderr). If the file "path" is > "limit" bytes, copy the
1386 // last "keep" bytes to offset 0 and truncate the rest. Since we could
1387 // be racing with other writers, this approach has the potential to
1388 // lose very small amounts of data. For security, only follow symlinks
1389 // if the path is /proc/self/fd/*
1390 GOOGLE_GLOG_DLL_DECL void TruncateLogFile(const char *path,
1391 int64 limit, int64 keep);
1393 // Truncate stdout and stderr if they are over the value specified by
1394 // --max_log_size; keep the final 1MB. This function has the same
1395 // race condition as TruncateLogFile.
1396 GOOGLE_GLOG_DLL_DECL void TruncateStdoutStderr();
1398 // Return the string representation of the provided LogSeverity level.
1400 GOOGLE_GLOG_DLL_DECL const char* GetLogSeverityName(LogSeverity severity);
1402 // ---------------------------------------------------------------------
1403 // Implementation details that are not useful to most clients
1404 // ---------------------------------------------------------------------
1406 // A Logger is the interface used by logging modules to emit entries
1407 // to a log. A typical implementation will dump formatted data to a
1408 // sequence of files. We also provide interfaces that will forward
1409 // the data to another thread so that the invoker never blocks.
1410 // Implementations should be thread-safe since the logging system
1411 // will write to them from multiple threads.
1415 class GOOGLE_GLOG_DLL_DECL Logger {
1419 // Writes "message[0,message_len-1]" corresponding to an event that
1420 // occurred at "timestamp". If "force_flush" is true, the log file
1421 // is flushed immediately.
1423 // The input message has already been formatted as deemed
1424 // appropriate by the higher level logging facility. For example,
1425 // textual log messages already contain timestamps, and the
1426 // file:linenumber header.
1427 virtual void Write(bool force_flush,
1429 const char* message,
1430 int message_len) = 0;
1432 // Flush any buffered messages
1433 virtual void Flush() = 0;
1435 // Get the current LOG file size.
1436 // The returned value is approximate since some
1437 // logged data may not have been flushed to disk yet.
1438 virtual uint32 LogSize() = 0;
1441 // Get the logger for the specified severity level. The logger
1442 // remains the property of the logging module and should not be
1443 // deleted by the caller. Thread-safe.
1444 extern GOOGLE_GLOG_DLL_DECL Logger* GetLogger(LogSeverity level);
1446 // Set the logger for the specified severity level. The logger
1447 // becomes the property of the logging module and should not
1448 // be deleted by the caller. Thread-safe.
1449 extern GOOGLE_GLOG_DLL_DECL void SetLogger(LogSeverity level, Logger* logger);
1453 // glibc has traditionally implemented two incompatible versions of
1454 // strerror_r(). There is a poorly defined convention for picking the
1455 // version that we want, but it is not clear whether it even works with
1456 // all versions of glibc.
1457 // So, instead, we provide this wrapper that automatically detects the
1458 // version that is in use, and then implements POSIX semantics.
1459 // N.B. In addition to what POSIX says, we also guarantee that "buf" will
1460 // be set to an empty string, if this function failed. This means, in most
1461 // cases, you do not need to check the error code and you can directly
1462 // use the value of "buf". It will never have an undefined value.
1463 GOOGLE_GLOG_DLL_DECL int posix_strerror_r(int err, char *buf, size_t len);
1466 // A class for which we define operator<<, which does nothing.
1467 class GOOGLE_GLOG_DLL_DECL NullStream : public LogMessage::LogStream {
1469 // Initialize the LogStream so the messages can be written somewhere
1470 // (they'll never be actually displayed). This will be needed if a
1471 // NullStream& is implicitly converted to LogStream&, in which case
1472 // the overloaded NullStream::operator<< will not be invoked.
1473 NullStream() : LogMessage::LogStream(message_buffer_, 1, 0) { }
1474 NullStream(const char* /*file*/, int /*line*/,
1475 const CheckOpString& /*result*/) :
1476 LogMessage::LogStream(message_buffer_, 1, 0) { }
1477 NullStream &stream() { return *this; }
1479 // A very short buffer for messages (which we discard anyway). This
1480 // will be needed if NullStream& converted to LogStream& (e.g. as a
1481 // result of a conditional expression).
1482 char message_buffer_[2];
1485 // Do nothing. This operator is inline, allowing the message to be
1486 // compiled away. The message will not be compiled away if we do
1487 // something like (flag ? LOG(INFO) : LOG(ERROR)) << message; when
1488 // SKIP_LOG=WARNING. In those cases, NullStream will be implicitly
1489 // converted to LogStream and the message will be computed and then
1490 // quietly discarded.
1492 inline NullStream& operator<<(NullStream &str, const T &) { return str; }
1494 // Similar to NullStream, but aborts the program (without stack
1495 // trace), like LogMessageFatal.
1496 class GOOGLE_GLOG_DLL_DECL NullStreamFatal : public NullStream {
1498 NullStreamFatal() { }
1499 NullStreamFatal(const char* file, int line, const CheckOpString& result) :
1500 NullStream(file, line, result) { }
1501 ~NullStreamFatal() { _exit(1); }
1504 // Install a signal handler that will dump signal information and a stack
1505 // trace when the program crashes on certain signals. We'll install the
1506 // signal handler for the following signals.
1508 // SIGSEGV, SIGILL, SIGFPE, SIGABRT, SIGBUS, and SIGTERM.
1510 // By default, the signal handler will write the failure dump to the
1511 // standard error. You can customize the destination by installing your
1512 // own writer function by InstallFailureWriter() below.
1514 // Note on threading:
1516 // The function should be called before threads are created, if you want
1517 // to use the failure signal handler for all threads. The stack trace
1518 // will be shown only for the thread that receives the signal. In other
1519 // words, stack traces of other threads won't be shown.
1520 GOOGLE_GLOG_DLL_DECL void InstallFailureSignalHandler();
1522 // Installs a function that is used for writing the failure dump. "data"
1523 // is the pointer to the beginning of a message to be written, and "size"
1524 // is the size of the message. You should not expect the data is
1525 // terminated with '\0'.
1526 GOOGLE_GLOG_DLL_DECL void InstallFailureWriter(
1527 void (*writer)(const char* data, int size));
1531 #endif // _LOGGING_H_