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 " << 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 COUNTER value is used to
163 // 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 " << 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 " << 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 " << 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 " << 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 " << 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::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::WARNING)
384 #define LOG_TO_STRING_WARNING(message) google::LogMessage( \
385 __FILE__, __LINE__, google::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::ERROR)
394 #define LOG_TO_STRING_ERROR(message) google::LogMessage( \
395 __FILE__, __LINE__, google::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::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 LogMessage( \
417 __FILE__, __LINE__, google::FATAL)
419 #define COMPACT_GOOGLE_LOG_DFATAL google::NullStreamFatal()
422 #define GOOGLE_LOG_INFO(counter) google::LogMessage(__FILE__, __LINE__, google::INFO, counter, &google::LogMessage::SendToLog)
423 #define SYSLOG_INFO(counter) \
424 google::LogMessage(__FILE__, __LINE__, google::INFO, counter, \
425 &google::LogMessage::SendToSyslogAndLog)
426 #define GOOGLE_LOG_WARNING(counter) \
427 google::LogMessage(__FILE__, __LINE__, google::WARNING, counter, \
428 &google::LogMessage::SendToLog)
429 #define SYSLOG_WARNING(counter) \
430 google::LogMessage(__FILE__, __LINE__, google::WARNING, counter, \
431 &google::LogMessage::SendToSyslogAndLog)
432 #define GOOGLE_LOG_ERROR(counter) \
433 google::LogMessage(__FILE__, __LINE__, google::ERROR, counter, \
434 &google::LogMessage::SendToLog)
435 #define SYSLOG_ERROR(counter) \
436 google::LogMessage(__FILE__, __LINE__, google::ERROR, counter, \
437 &google::LogMessage::SendToSyslogAndLog)
438 #define GOOGLE_LOG_FATAL(counter) \
439 google::LogMessage(__FILE__, __LINE__, google::FATAL, counter, \
440 &google::LogMessage::SendToLog)
441 #define SYSLOG_FATAL(counter) \
442 google::LogMessage(__FILE__, __LINE__, google::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__, 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 // Install a function which will be called after LOG(FATAL).
490 GOOGLE_GLOG_DLL_DECL void InstallFailureFunction(void (*fail_func)());
492 class LogSink; // defined below
494 // If a non-NULL sink pointer is given, we push this message to that sink.
495 // For LOG_TO_SINK we then do normal LOG(severity) logging as well.
496 // This is useful for capturing messages and passing/storing them
497 // somewhere more specific than the global log of the process.
500 // LogSeverity severity;
501 // The cast is to disambiguate NULL arguments.
502 #define LOG_TO_SINK(sink, severity) \
503 google::LogMessage( \
504 __FILE__, __LINE__, \
506 static_cast<google::LogSink*>(sink), true).stream()
507 #define LOG_TO_SINK_BUT_NOT_TO_LOGFILE(sink, severity) \
508 google::LogMessage( \
509 __FILE__, __LINE__, \
511 static_cast<google::LogSink*>(sink), false).stream()
513 // If a non-NULL string pointer is given, we write this message to that string.
514 // We then do normal LOG(severity) logging as well.
515 // This is useful for capturing messages and storing them somewhere more
516 // specific than the global log of the process.
519 // LogSeverity severity;
520 // The cast is to disambiguate NULL arguments.
521 // NOTE: LOG(severity) expands to LogMessage().stream() for the specified
523 #define LOG_TO_STRING(severity, message) \
524 LOG_TO_STRING_##severity(static_cast<string*>(message)).stream()
526 // If a non-NULL pointer is given, we push the message onto the end
527 // of a vector of strings; otherwise, we report it with LOG(severity).
528 // This is handy for capturing messages and perhaps passing them back
529 // to the caller, rather than reporting them immediately.
531 // LogSeverity severity;
532 // vector<string> *outvec;
533 // The cast is to disambiguate NULL arguments.
534 #define LOG_STRING(severity, outvec) \
535 LOG_TO_STRING_##severity(static_cast<vector<string>*>(outvec)).stream()
537 #define LOG_IF(severity, condition) \
538 !(condition) ? (void) 0 : google::LogMessageVoidify() & LOG(severity)
539 #define SYSLOG_IF(severity, condition) \
540 !(condition) ? (void) 0 : google::LogMessageVoidify() & SYSLOG(severity)
542 #define LOG_ASSERT(condition) \
543 LOG_IF(FATAL, !(condition)) << "Assert failed: " #condition
544 #define SYSLOG_ASSERT(condition) \
545 SYSLOG_IF(FATAL, !(condition)) << "Assert failed: " #condition
547 // CHECK dies with a fatal error if condition is not true. It is *not*
548 // controlled by NDEBUG, so the check will be executed regardless of
549 // compilation mode. Therefore, it is safe to do things like:
550 // CHECK(fp->Write(x) == 4)
551 #define CHECK(condition) \
552 LOG_IF(FATAL, GOOGLE_PREDICT_BRANCH_NOT_TAKEN(!(condition))) \
553 << "Check failed: " #condition " "
555 // A container for a string pointer which can be evaluated to a bool -
556 // true iff the pointer is NULL.
557 struct CheckOpString {
558 CheckOpString(std::string* str) : str_(str) { }
559 // No destructor: if str_ is non-NULL, we're about to LOG(FATAL),
560 // so there's no point in cleaning up str_.
561 operator bool() const {
562 return GOOGLE_PREDICT_BRANCH_NOT_TAKEN(str_ != NULL);
567 // Function is overloaded for integral types to allow static const
568 // integrals declared in classes and not defined to be used as arguments to
569 // CHECK* macros. It's not encouraged though.
571 inline const T& GetReferenceableValue(const T& t) { return t; }
572 inline char GetReferenceableValue(char t) { return t; }
573 inline unsigned char GetReferenceableValue(unsigned char t) { return t; }
574 inline signed char GetReferenceableValue(signed char t) { return t; }
575 inline short GetReferenceableValue(short t) { return t; }
576 inline unsigned short GetReferenceableValue(unsigned short t) { return t; }
577 inline int GetReferenceableValue(int t) { return t; }
578 inline unsigned int GetReferenceableValue(unsigned int t) { return t; }
579 inline long GetReferenceableValue(long t) { return t; }
580 inline unsigned long GetReferenceableValue(unsigned long t) { return t; }
581 inline long long GetReferenceableValue(long long t) { return t; }
582 inline unsigned long long GetReferenceableValue(unsigned long long t) {
586 // This is a dummy class to define the following operator.
587 struct DummyClassToDefineOperator {};
591 // Define global operator<< to declare using ::operator<<.
592 // This declaration will allow use to use CHECK macros for user
593 // defined classes which have operator<< (e.g., stl_logging.h).
594 inline std::ostream& operator<<(
595 std::ostream& out, const google::DummyClassToDefineOperator&) {
601 // Build the error message string.
602 template<class t1, class t2>
603 std::string* MakeCheckOpString(const t1& v1, const t2& v2, const char* names) {
604 // It means that we cannot use stl_logging if compiler doesn't
605 // support using expression for operator.
606 // TODO(hamaji): Figure out a way to fix.
611 ss << names << " (" << v1 << " vs. " << v2 << ")";
612 return new std::string(ss.str(), ss.pcount());
615 // Helper functions for CHECK_OP macro.
616 // The (int, int) specialization works around the issue that the compiler
617 // will not instantiate the template version of the function on values of
618 // unnamed enum type - see comment below.
619 #define DEFINE_CHECK_OP_IMPL(name, op) \
620 template <class t1, class t2> \
621 inline std::string* Check##name##Impl(const t1& v1, const t2& v2, \
622 const char* names) { \
623 if (v1 op v2) return NULL; \
624 else return MakeCheckOpString(v1, v2, names); \
626 inline std::string* Check##name##Impl(int v1, int v2, const char* names) { \
627 return Check##name##Impl<int, int>(v1, v2, names); \
630 // Use _EQ, _NE, _LE, etc. in case the file including base/logging.h
631 // provides its own #defines for the simpler names EQ, NE, LE, etc.
632 // This happens if, for example, those are used as token names in a
634 DEFINE_CHECK_OP_IMPL(_EQ, ==)
635 DEFINE_CHECK_OP_IMPL(_NE, !=)
636 DEFINE_CHECK_OP_IMPL(_LE, <=)
637 DEFINE_CHECK_OP_IMPL(_LT, < )
638 DEFINE_CHECK_OP_IMPL(_GE, >=)
639 DEFINE_CHECK_OP_IMPL(_GT, > )
640 #undef DEFINE_CHECK_OP_IMPL
642 // Helper macro for binary operators.
643 // Don't use this macro directly in your code, use CHECK_EQ et al below.
645 #if defined(STATIC_ANALYSIS)
646 // Only for static analysis tool to know that it is equivalent to assert
647 #define CHECK_OP_LOG(name, op, val1, val2, log) CHECK((val1) op (val2))
648 #elif !defined(NDEBUG)
649 // In debug mode, avoid constructing CheckOpStrings if possible,
650 // to reduce the overhead of CHECK statments by 2x.
651 // Real DCHECK-heavy tests have seen 1.5x speedups.
653 // The meaning of "string" might be different between now and
654 // when this macro gets invoked (e.g., if someone is experimenting
655 // with other string implementations that get defined after this
656 // file is included). Save the current meaning now and use it
658 typedef std::string _Check_string;
659 #define CHECK_OP_LOG(name, op, val1, val2, log) \
660 while (google::_Check_string* _result = \
661 google::Check##name##Impl( \
662 google::GetReferenceableValue(val1), \
663 google::GetReferenceableValue(val2), \
664 #val1 " " #op " " #val2)) \
665 log(__FILE__, __LINE__, \
666 google::CheckOpString(_result)).stream()
668 // In optimized mode, use CheckOpString to hint to compiler that
669 // the while condition is unlikely.
670 #define CHECK_OP_LOG(name, op, val1, val2, log) \
671 while (google::CheckOpString _result = \
672 google::Check##name##Impl( \
673 google::GetReferenceableValue(val1), \
674 google::GetReferenceableValue(val2), \
675 #val1 " " #op " " #val2)) \
676 log(__FILE__, __LINE__, _result).stream()
677 #endif // STATIC_ANALYSIS, !NDEBUG
679 #if GOOGLE_STRIP_LOG <= 3
680 #define CHECK_OP(name, op, val1, val2) \
681 CHECK_OP_LOG(name, op, val1, val2, google::LogMessageFatal)
683 #define CHECK_OP(name, op, val1, val2) \
684 CHECK_OP_LOG(name, op, val1, val2, google::NullStreamFatal)
685 #endif // STRIP_LOG <= 3
687 // Equality/Inequality checks - compare two values, and log a FATAL message
688 // including the two values when the result is not as expected. The values
689 // must have operator<<(ostream, ...) defined.
691 // You may append to the error message like so:
692 // CHECK_NE(1, 2) << ": The world must be ending!";
694 // We are very careful to ensure that each argument is evaluated exactly
695 // once, and that anything which is legal to pass as a function argument is
696 // legal here. In particular, the arguments may be temporary expressions
697 // which will end up being destroyed at the end of the apparent statement,
699 // CHECK_EQ(string("abc")[1], 'b');
701 // WARNING: These don't compile correctly if one of the arguments is a pointer
702 // and the other is NULL. To work around this, simply static_cast NULL to the
703 // type of the desired pointer.
705 #define CHECK_EQ(val1, val2) CHECK_OP(_EQ, ==, val1, val2)
706 #define CHECK_NE(val1, val2) CHECK_OP(_NE, !=, val1, val2)
707 #define CHECK_LE(val1, val2) CHECK_OP(_LE, <=, val1, val2)
708 #define CHECK_LT(val1, val2) CHECK_OP(_LT, < , val1, val2)
709 #define CHECK_GE(val1, val2) CHECK_OP(_GE, >=, val1, val2)
710 #define CHECK_GT(val1, val2) CHECK_OP(_GT, > , val1, val2)
712 // Check that the input is non NULL. This very useful in constructor
713 // initializer lists.
715 #define CHECK_NOTNULL(val) \
716 google::CheckNotNull(__FILE__, __LINE__, "'" #val "' Must be non NULL", (val))
718 // Helper functions for string comparisons.
719 // To avoid bloat, the definitions are in logging.cc.
720 #define DECLARE_CHECK_STROP_IMPL(func, expected) \
721 GOOGLE_GLOG_DLL_DECL std::string* Check##func##expected##Impl( \
722 const char* s1, const char* s2, const char* names);
723 DECLARE_CHECK_STROP_IMPL(strcmp, true)
724 DECLARE_CHECK_STROP_IMPL(strcmp, false)
725 DECLARE_CHECK_STROP_IMPL(strcasecmp, true)
726 DECLARE_CHECK_STROP_IMPL(strcasecmp, false)
727 #undef DECLARE_CHECK_STROP_IMPL
729 // Helper macro for string comparisons.
730 // Don't use this macro directly in your code, use CHECK_STREQ et al below.
731 #define CHECK_STROP(func, op, expected, s1, s2) \
732 while (google::CheckOpString _result = \
733 google::Check##func##expected##Impl((s1), (s2), \
734 #s1 " " #op " " #s2)) \
735 LOG(FATAL) << *_result.str_
738 // String (char*) equality/inequality checks.
739 // CASE versions are case-insensitive.
741 // Note that "s1" and "s2" may be temporary strings which are destroyed
742 // by the compiler at the end of the current "full expression"
743 // (e.g. CHECK_STREQ(Foo().c_str(), Bar().c_str())).
745 #define CHECK_STREQ(s1, s2) CHECK_STROP(strcmp, ==, true, s1, s2)
746 #define CHECK_STRNE(s1, s2) CHECK_STROP(strcmp, !=, false, s1, s2)
747 #define CHECK_STRCASEEQ(s1, s2) CHECK_STROP(strcasecmp, ==, true, s1, s2)
748 #define CHECK_STRCASENE(s1, s2) CHECK_STROP(strcasecmp, !=, false, s1, s2)
750 #define CHECK_INDEX(I,A) CHECK(I < (sizeof(A)/sizeof(A[0])))
751 #define CHECK_BOUND(B,A) CHECK(B <= (sizeof(A)/sizeof(A[0])))
753 #define CHECK_DOUBLE_EQ(val1, val2) \
755 CHECK_LE((val1), (val2)+0.000000000000001L); \
756 CHECK_GE((val1), (val2)-0.000000000000001L); \
759 #define CHECK_NEAR(val1, val2, margin) \
761 CHECK_LE((val1), (val2)+(margin)); \
762 CHECK_GE((val1), (val2)-(margin)); \
765 // perror()..googly style!
767 // PLOG() and PLOG_IF() and PCHECK() behave exactly like their LOG* and
768 // CHECK equivalents with the addition that they postpend a description
769 // of the current state of errno to their output lines.
771 #define PLOG(severity) GOOGLE_PLOG(severity, 0).stream()
773 #define GOOGLE_PLOG(severity, counter) \
774 google::ErrnoLogMessage( \
775 __FILE__, __LINE__, google::severity, counter, \
776 &google::LogMessage::SendToLog)
778 #define PLOG_IF(severity, condition) \
779 !(condition) ? (void) 0 : google::LogMessageVoidify() & PLOG(severity)
781 // A CHECK() macro that postpends errno if the condition is false. E.g.
783 // if (poll(fds, nfds, timeout) == -1) { PCHECK(errno == EINTR); ... }
784 #define PCHECK(condition) \
785 PLOG_IF(FATAL, GOOGLE_PREDICT_BRANCH_NOT_TAKEN(!(condition))) \
786 << "Check failed: " #condition " "
788 // A CHECK() macro that lets you assert the success of a function that
789 // returns -1 and sets errno in case of an error. E.g.
791 // CHECK_ERR(mkdir(path, 0700));
795 // int fd = open(filename, flags); CHECK_ERR(fd) << ": open " << filename;
796 #define CHECK_ERR(invocation) \
797 PLOG_IF(FATAL, GOOGLE_PREDICT_BRANCH_NOT_TAKEN((invocation) == -1)) \
800 // Use macro expansion to create, for each use of LOG_EVERY_N(), static
801 // variables with the __LINE__ expansion as part of the variable name.
802 #define LOG_EVERY_N_VARNAME(base, line) LOG_EVERY_N_VARNAME_CONCAT(base, line)
803 #define LOG_EVERY_N_VARNAME_CONCAT(base, line) base ## line
805 #define LOG_OCCURRENCES LOG_EVERY_N_VARNAME(occurrences_, __LINE__)
806 #define LOG_OCCURRENCES_MOD_N LOG_EVERY_N_VARNAME(occurrences_mod_n_, __LINE__)
808 #define SOME_KIND_OF_LOG_EVERY_N(severity, n, what_to_do) \
809 static int LOG_OCCURRENCES = 0, LOG_OCCURRENCES_MOD_N = 0; \
811 if (++LOG_OCCURRENCES_MOD_N > n) LOG_OCCURRENCES_MOD_N -= n; \
812 if (LOG_OCCURRENCES_MOD_N == 1) \
813 google::LogMessage( \
814 __FILE__, __LINE__, google::severity, LOG_OCCURRENCES, \
815 &what_to_do).stream()
817 #define SOME_KIND_OF_LOG_IF_EVERY_N(severity, condition, n, what_to_do) \
818 static int LOG_OCCURRENCES = 0, LOG_OCCURRENCES_MOD_N = 0; \
821 ((LOG_OCCURRENCES_MOD_N=(LOG_OCCURRENCES_MOD_N + 1) % n) == (1 % n))) \
822 google::LogMessage( \
823 __FILE__, __LINE__, google::severity, LOG_OCCURRENCES, \
824 &what_to_do).stream()
826 #define SOME_KIND_OF_PLOG_EVERY_N(severity, n, what_to_do) \
827 static int LOG_OCCURRENCES = 0, LOG_OCCURRENCES_MOD_N = 0; \
829 if (++LOG_OCCURRENCES_MOD_N > n) LOG_OCCURRENCES_MOD_N -= n; \
830 if (LOG_OCCURRENCES_MOD_N == 1) \
831 google::ErrnoLogMessage( \
832 __FILE__, __LINE__, google::severity, LOG_OCCURRENCES, \
833 &what_to_do).stream()
835 #define SOME_KIND_OF_LOG_FIRST_N(severity, n, what_to_do) \
836 static int LOG_OCCURRENCES = 0; \
837 if (LOG_OCCURRENCES <= n) \
839 if (LOG_OCCURRENCES <= n) \
840 google::LogMessage( \
841 __FILE__, __LINE__, google::severity, LOG_OCCURRENCES, \
842 &what_to_do).stream()
844 namespace glog_internal_namespace_ {
846 struct CompileAssert {
849 } // namespace glog_internal_namespace_
851 #define GOOGLE_GLOG_COMPILE_ASSERT(expr, msg) \
852 typedef google::glog_internal_namespace_::CompileAssert<(bool(expr))> msg[bool(expr) ? 1 : -1]
854 #define LOG_EVERY_N(severity, n) \
855 GOOGLE_GLOG_COMPILE_ASSERT(google::severity < \
856 google::NUM_SEVERITIES, \
857 INVALID_REQUESTED_LOG_SEVERITY); \
858 SOME_KIND_OF_LOG_EVERY_N(severity, (n), google::LogMessage::SendToLog)
860 #define SYSLOG_EVERY_N(severity, n) \
861 SOME_KIND_OF_LOG_EVERY_N(severity, (n), google::LogMessage::SendToSyslogAndLog)
863 #define PLOG_EVERY_N(severity, n) \
864 SOME_KIND_OF_PLOG_EVERY_N(severity, (n), google::LogMessage::SendToLog)
866 #define LOG_FIRST_N(severity, n) \
867 SOME_KIND_OF_LOG_FIRST_N(severity, (n), google::LogMessage::SendToLog)
869 #define LOG_IF_EVERY_N(severity, condition, n) \
870 SOME_KIND_OF_LOG_IF_EVERY_N(severity, (condition), (n), google::LogMessage::SendToLog)
872 // We want the special COUNTER value available for LOG_EVERY_X()'ed messages
873 enum PRIVATE_Counter {COUNTER};
876 // Plus some debug-logging macros that get compiled to nothing for production
880 #define DLOG(severity) LOG(severity)
881 #define DVLOG(verboselevel) VLOG(verboselevel)
882 #define DLOG_IF(severity, condition) LOG_IF(severity, condition)
883 #define DLOG_EVERY_N(severity, n) LOG_EVERY_N(severity, n)
884 #define DLOG_IF_EVERY_N(severity, condition, n) \
885 LOG_IF_EVERY_N(severity, condition, n)
886 #define DLOG_ASSERT(condition) LOG_ASSERT(condition)
888 // debug-only checking. not executed in NDEBUG mode.
889 #define DCHECK(condition) CHECK(condition)
890 #define DCHECK_EQ(val1, val2) CHECK_EQ(val1, val2)
891 #define DCHECK_NE(val1, val2) CHECK_NE(val1, val2)
892 #define DCHECK_LE(val1, val2) CHECK_LE(val1, val2)
893 #define DCHECK_LT(val1, val2) CHECK_LT(val1, val2)
894 #define DCHECK_GE(val1, val2) CHECK_GE(val1, val2)
895 #define DCHECK_GT(val1, val2) CHECK_GT(val1, val2)
896 #define DCHECK_STREQ(str1, str2) CHECK_STREQ(str1, str2)
897 #define DCHECK_STRCASEEQ(str1, str2) CHECK_STRCASEEQ(str1, str2)
898 #define DCHECK_STRNE(str1, str2) CHECK_STRNE(str1, str2)
899 #define DCHECK_STRCASENE(str1, str2) CHECK_STRCASENE(str1, str2)
903 #define DLOG(severity) \
904 true ? (void) 0 : google::LogMessageVoidify() & LOG(severity)
906 #define DVLOG(verboselevel) \
907 (true || !VLOG_IS_ON(verboselevel)) ?\
908 (void) 0 : google::LogMessageVoidify() & LOG(INFO)
910 #define DLOG_IF(severity, condition) \
911 (true || !(condition)) ? (void) 0 : google::LogMessageVoidify() & LOG(severity)
913 #define DLOG_EVERY_N(severity, n) \
914 true ? (void) 0 : google::LogMessageVoidify() & LOG(severity)
916 #define DLOG_IF_EVERY_N(severity, condition, n) \
917 (true || !(condition))? (void) 0 : google::LogMessageVoidify() & LOG(severity)
919 #define DLOG_ASSERT(condition) \
920 true ? (void) 0 : LOG_ASSERT(condition)
922 #define DCHECK(condition) \
926 #define DCHECK_EQ(val1, val2) \
930 #define DCHECK_NE(val1, val2) \
934 #define DCHECK_LE(val1, val2) \
938 #define DCHECK_LT(val1, val2) \
942 #define DCHECK_GE(val1, val2) \
946 #define DCHECK_GT(val1, val2) \
950 #define DCHECK_STREQ(str1, str2) \
952 CHECK_STREQ(str1, str2)
954 #define DCHECK_STRCASEEQ(str1, str2) \
956 CHECK_STRCASEEQ(str1, str2)
958 #define DCHECK_STRNE(str1, str2) \
960 CHECK_STRNE(str1, str2)
962 #define DCHECK_STRCASENE(str1, str2) \
964 CHECK_STRCASENE(str1, str2)
969 // Log only in verbose mode.
971 #define VLOG(verboselevel) LOG_IF(INFO, VLOG_IS_ON(verboselevel))
973 #define VLOG_IF(verboselevel, condition) \
974 LOG_IF(INFO, (condition) && VLOG_IS_ON(verboselevel))
976 #define VLOG_EVERY_N(verboselevel, n) \
977 LOG_IF_EVERY_N(INFO, VLOG_IS_ON(verboselevel), n)
979 #define VLOG_IF_EVERY_N(verboselevel, condition, n) \
980 LOG_IF_EVERY_N(INFO, (condition) && VLOG_IS_ON(verboselevel), n)
983 // This class more or less represents a particular log message. You
984 // create an instance of LogMessage and then stream stuff to it.
985 // When you finish streaming to it, ~LogMessage is called and the
986 // full message gets streamed to the appropriate destination.
988 // You shouldn't actually use LogMessage's constructor to log things,
989 // though. You should use the LOG() macro (and variants thereof)
991 class GOOGLE_GLOG_DLL_DECL LogMessage {
994 // Passing kNoLogPrefix for the line number disables the
995 // log-message prefix. Useful for using the LogMessage
996 // infrastructure as a printing utility. See also the --log_prefix
997 // flag for controlling the log-message prefix on an
998 // application-wide basis.
1002 // LogStream inherit from non-DLL-exported class (std::ostrstream)
1003 // and VC++ produces a warning for this situation.
1004 // However, MSDN says "C4275 can be ignored in Microsoft Visual C++
1005 // 2005 if you are deriving from a type in the Standard C++ Library"
1006 // http://msdn.microsoft.com/en-us/library/3tdb471s(VS.80).aspx
1007 // Let's just ignore the warning.
1009 # pragma warning(disable: 4275)
1011 class GOOGLE_GLOG_DLL_DECL LogStream : public std::ostrstream {
1013 # pragma warning(default: 4275)
1016 LogStream(char *buf, int len, int ctr)
1017 : ostrstream(buf, len),
1022 int ctr() const { return ctr_; }
1023 void set_ctr(int ctr) { ctr_ = ctr; }
1024 LogStream* self() const { return self_; }
1027 int ctr_; // Counter hack (for the LOG_EVERY_X() macro)
1028 LogStream *self_; // Consistency check hack
1032 // icc 8 requires this typedef to avoid an internal compiler error.
1033 typedef void (LogMessage::*SendMethod)();
1035 LogMessage(const char* file, int line, LogSeverity severity, int ctr,
1036 SendMethod send_method);
1038 // Two special constructors that generate reduced amounts of code at
1039 // LOG call sites for common cases.
1041 // Used for LOG(INFO): Implied are:
1042 // severity = INFO, ctr = 0, send_method = &LogMessage::SendToLog.
1044 // Using this constructor instead of the more complex constructor above
1045 // saves 19 bytes per call site.
1046 LogMessage(const char* file, int line);
1048 // Used for LOG(severity) where severity != INFO. Implied
1049 // are: ctr = 0, send_method = &LogMessage::SendToLog
1051 // Using this constructor instead of the more complex constructor above
1052 // saves 17 bytes per call site.
1053 LogMessage(const char* file, int line, LogSeverity severity);
1055 // Constructor to log this message to a specified sink (if not NULL).
1056 // Implied are: ctr = 0, send_method = &LogMessage::SendToSinkAndLog if
1057 // also_send_to_log is true, send_method = &LogMessage::SendToSink otherwise.
1058 LogMessage(const char* file, int line, LogSeverity severity, LogSink* sink,
1059 bool also_send_to_log);
1061 // Constructor where we also give a vector<string> pointer
1062 // for storing the messages (if the pointer is not NULL).
1063 // Implied are: ctr = 0, send_method = &LogMessage::SaveOrSendToLog.
1064 LogMessage(const char* file, int line, LogSeverity severity,
1065 std::vector<std::string>* outvec);
1067 // Constructor where we also give a string pointer for storing the
1068 // message (if the pointer is not NULL). Implied are: ctr = 0,
1069 // send_method = &LogMessage::WriteToStringAndLog.
1070 LogMessage(const char* file, int line, LogSeverity severity,
1071 std::string* message);
1073 // A special constructor used for check failures
1074 LogMessage(const char* file, int line, const CheckOpString& result);
1078 // Flush a buffered message to the sink set in the constructor. Always
1079 // called by the destructor, it may also be called from elsewhere if
1080 // needed. Only the first call is actioned; any later ones are ignored.
1083 // An arbitrary limit on the length of a single log message. This
1084 // is so that streaming can be done more efficiently.
1085 static const size_t kMaxLogMessageLen;
1087 // Theses should not be called directly outside of logging.*,
1088 // only passed as SendMethod arguments to other LogMessage methods:
1089 void SendToLog(); // Actually dispatch to the logs
1090 void SendToSyslogAndLog(); // Actually dispatch to syslog and the logs
1092 // Call abort() or similar to perform LOG(FATAL) crash.
1093 static void Fail() ;
1095 std::ostream& stream() { return *(data_->stream_); }
1097 int preserved_errno() const { return data_->preserved_errno_; }
1099 // Must be called without the log_mutex held. (L < log_mutex)
1100 static int64 num_messages(int severity);
1103 // Fully internal SendMethod cases:
1104 void SendToSinkAndLog(); // Send to sink if provided and dispatch to the logs
1105 void SendToSink(); // Send to sink if provided, do nothing otherwise.
1107 // Write to string if provided and dispatch to the logs.
1108 void WriteToStringAndLog();
1110 void SaveOrSendToLog(); // Save to stringvec if provided, else to logs
1112 void Init(const char* file, int line, LogSeverity severity,
1113 void (LogMessage::*send_method)());
1115 // Used to fill in crash information during LOG(FATAL) failures.
1116 void RecordCrashReason(glog_internal_namespace_::CrashReason* reason);
1118 // Counts of messages sent at each priority:
1119 static int64 num_messages_[NUM_SEVERITIES]; // under log_mutex
1121 // We keep the data in a separate struct so that each instance of
1122 // LogMessage uses less stack space.
1123 struct GOOGLE_GLOG_DLL_DECL LogMessageData {
1124 LogMessageData() {};
1126 int preserved_errno_; // preserved errno
1128 char* message_text_; // Complete message text (points to selected buffer)
1129 LogStream* stream_alloc_;
1131 char severity_; // What level is this LogMessage logged at?
1132 int line_; // line number where logging call is.
1133 void (LogMessage::*send_method_)(); // Call this in destructor to send
1134 union { // At most one of these is used: union to keep the size low.
1135 LogSink* sink_; // NULL or sink to send message to
1136 std::vector<std::string>* outvec_; // NULL or vector to push message onto
1137 std::string* message_; // NULL or string to write message into
1139 time_t timestamp_; // Time of creation of LogMessage
1140 struct ::tm tm_time_; // Time of creation of LogMessage
1141 size_t num_prefix_chars_; // # of chars of prefix in this message
1142 size_t num_chars_to_log_; // # of chars of msg to send to log
1143 size_t num_chars_to_syslog_; // # of chars of msg to send to syslog
1144 const char* basename_; // basename of file that called LOG
1145 const char* fullname_; // fullname of file that called LOG
1146 bool has_been_flushed_; // false => data has not been flushed
1147 bool first_fatal_; // true => this was first fatal msg
1151 LogMessageData(const LogMessageData&);
1152 void operator=(const LogMessageData&);
1155 static LogMessageData fatal_msg_data_exclusive_;
1156 static LogMessageData fatal_msg_data_shared_;
1158 LogMessageData* allocated_;
1159 LogMessageData* data_;
1161 friend class LogDestination;
1163 LogMessage(const LogMessage&);
1164 void operator=(const LogMessage&);
1167 // This class happens to be thread-hostile because all instances share
1168 // a single data buffer, but since it can only be created just before
1169 // the process dies, we don't worry so much.
1170 class GOOGLE_GLOG_DLL_DECL LogMessageFatal : public LogMessage {
1172 LogMessageFatal(const char* file, int line);
1173 LogMessageFatal(const char* file, int line, const CheckOpString& result);
1174 ~LogMessageFatal() ;
1177 // A non-macro interface to the log facility; (useful
1178 // when the logging level is not a compile-time constant).
1179 inline void LogAtLevel(int const severity, std::string const &msg) {
1180 LogMessage(__FILE__, __LINE__, severity).stream() << msg;
1183 // A macro alternative of LogAtLevel. New code may want to use this
1184 // version since there are two advantages: 1. this version outputs the
1185 // file name and the line number where this macro is put like other
1186 // LOG macros, 2. this macro can be used as C++ stream.
1187 #define LOG_AT_LEVEL(severity) LogMessage(__FILE__, __LINE__, severity).stream()
1189 // A small helper for CHECK_NOTNULL().
1190 template <typename T>
1191 T* CheckNotNull(const char *file, int line, const char *names, T* t) {
1193 LogMessageFatal(file, line, new std::string(names));
1198 // Allow folks to put a counter in the LOG_EVERY_X()'ed messages. This
1199 // only works if ostream is a LogStream. If the ostream is not a
1200 // LogStream you'll get an assert saying as much at runtime.
1201 GOOGLE_GLOG_DLL_DECL std::ostream& operator<<(std::ostream &os,
1202 const PRIVATE_Counter&);
1205 // Derived class for PLOG*() above.
1206 class GOOGLE_GLOG_DLL_DECL ErrnoLogMessage : public LogMessage {
1209 ErrnoLogMessage(const char* file, int line, LogSeverity severity, int ctr,
1210 void (LogMessage::*send_method)());
1212 // Postpends ": strerror(errno) [errno]".
1216 ErrnoLogMessage(const ErrnoLogMessage&);
1217 void operator=(const ErrnoLogMessage&);
1221 // This class is used to explicitly ignore values in the conditional
1222 // logging macros. This avoids compiler warnings like "value computed
1223 // is not used" and "statement has no effect".
1225 class GOOGLE_GLOG_DLL_DECL LogMessageVoidify {
1227 LogMessageVoidify() { }
1228 // This has to be an operator with a precedence lower than << but
1230 void operator&(std::ostream&) { }
1234 // Flushes all log files that contains messages that are at least of
1235 // the specified severity level. Thread-safe.
1236 GOOGLE_GLOG_DLL_DECL void FlushLogFiles(LogSeverity min_severity);
1238 // Flushes all log files that contains messages that are at least of
1239 // the specified severity level. Thread-hostile because it ignores
1240 // locking -- used for catastrophic failures.
1241 GOOGLE_GLOG_DLL_DECL void FlushLogFilesUnsafe(LogSeverity min_severity);
1244 // Set the destination to which a particular severity level of log
1245 // messages is sent. If base_filename is "", it means "don't log this
1246 // severity". Thread-safe.
1248 GOOGLE_GLOG_DLL_DECL void SetLogDestination(LogSeverity severity,
1249 const char* base_filename);
1252 // Set the basename of the symlink to the latest log file at a given
1253 // severity. If symlink_basename is empty, do not make a symlink. If
1254 // you don't call this function, the symlink basename is the
1255 // invocation name of the program. Thread-safe.
1257 GOOGLE_GLOG_DLL_DECL void SetLogSymlink(LogSeverity severity,
1258 const char* symlink_basename);
1261 // Used to send logs to some other kind of destination
1262 // Users should subclass LogSink and override send to do whatever they want.
1263 // Implementations must be thread-safe because a shared instance will
1264 // be called from whichever thread ran the LOG(XXX) line.
1265 class GOOGLE_GLOG_DLL_DECL LogSink {
1269 // Sink's logging logic (message_len is such as to exclude '\n' at the end).
1270 // This method can't use LOG() or CHECK() as logging system mutex(s) are held
1271 // during this call.
1272 virtual void send(LogSeverity severity, const char* full_filename,
1273 const char* base_filename, int line,
1274 const struct ::tm* tm_time,
1275 const char* message, size_t message_len) = 0;
1277 // Redefine this to implement waiting for
1278 // the sink's logging logic to complete.
1279 // It will be called after each send() returns,
1280 // but before that LogMessage exits or crashes.
1281 // By default this function does nothing.
1282 // Using this function one can implement complex logic for send()
1283 // that itself involves logging; and do all this w/o causing deadlocks and
1284 // inconsistent rearrangement of log messages.
1285 // E.g. if a LogSink has thread-specific actions, the send() method
1286 // can simply add the message to a queue and wake up another thread that
1287 // handles real logging while itself making some LOG() calls;
1288 // WaitTillSent() can be implemented to wait for that logic to complete.
1289 // See our unittest for an example.
1290 virtual void WaitTillSent();
1292 // Returns the normal text output of the log message.
1293 // Can be useful to implement send().
1294 static std::string ToString(LogSeverity severity, const char* file, int line,
1295 const struct ::tm* tm_time,
1296 const char* message, size_t message_len);
1299 // Add or remove a LogSink as a consumer of logging data. Thread-safe.
1300 GOOGLE_GLOG_DLL_DECL void AddLogSink(LogSink *destination);
1301 GOOGLE_GLOG_DLL_DECL void RemoveLogSink(LogSink *destination);
1304 // Specify an "extension" added to the filename specified via
1305 // SetLogDestination. This applies to all severity levels. It's
1306 // often used to append the port we're listening on to the logfile
1307 // name. Thread-safe.
1309 GOOGLE_GLOG_DLL_DECL void SetLogFilenameExtension(
1310 const char* filename_extension);
1313 // Make it so that all log messages of at least a particular severity
1314 // are logged to stderr (in addition to logging to the usual log
1315 // file(s)). Thread-safe.
1317 GOOGLE_GLOG_DLL_DECL void SetStderrLogging(LogSeverity min_severity);
1320 // Make it so that all log messages go only to stderr. Thread-safe.
1322 GOOGLE_GLOG_DLL_DECL void LogToStderr();
1325 // Make it so that all log messages of at least a particular severity are
1326 // logged via email to a list of addresses (in addition to logging to the
1327 // usual log file(s)). The list of addresses is just a string containing
1328 // the email addresses to send to (separated by spaces, say). Thread-safe.
1330 GOOGLE_GLOG_DLL_DECL void SetEmailLogging(LogSeverity min_severity,
1331 const char* addresses);
1333 // A simple function that sends email. dest is a commma-separated
1334 // list of addressess. Thread-safe.
1335 GOOGLE_GLOG_DLL_DECL bool SendEmail(const char *dest,
1336 const char *subject, const char *body);
1338 GOOGLE_GLOG_DLL_DECL const std::vector<std::string>& GetLoggingDirectories();
1340 // For tests only: Clear the internal [cached] list of logging directories to
1341 // force a refresh the next time GetLoggingDirectories is called.
1343 void TestOnly_ClearLoggingDirectoriesList();
1345 // Returns a set of existing temporary directories, which will be a
1346 // subset of the directories returned by GetLogginDirectories().
1348 GOOGLE_GLOG_DLL_DECL void GetExistingTempDirectories(
1349 std::vector<std::string>* list);
1351 // Print any fatal message again -- useful to call from signal handler
1352 // so that the last thing in the output is the fatal message.
1353 // Thread-hostile, but a race is unlikely.
1354 GOOGLE_GLOG_DLL_DECL void ReprintFatalMessage();
1356 // Truncate a log file that may be the append-only output of multiple
1357 // processes and hence can't simply be renamed/reopened (typically a
1358 // stdout/stderr). If the file "path" is > "limit" bytes, copy the
1359 // last "keep" bytes to offset 0 and truncate the rest. Since we could
1360 // be racing with other writers, this approach has the potential to
1361 // lose very small amounts of data. For security, only follow symlinks
1362 // if the path is /proc/self/fd/*
1363 GOOGLE_GLOG_DLL_DECL void TruncateLogFile(const char *path,
1364 int64 limit, int64 keep);
1366 // Truncate stdout and stderr if they are over the value specified by
1367 // --max_log_size; keep the final 1MB. This function has the same
1368 // race condition as TruncateLogFile.
1369 GOOGLE_GLOG_DLL_DECL void TruncateStdoutStderr();
1371 // Return the string representation of the provided LogSeverity level.
1373 GOOGLE_GLOG_DLL_DECL const char* GetLogSeverityName(LogSeverity severity);
1375 // ---------------------------------------------------------------------
1376 // Implementation details that are not useful to most clients
1377 // ---------------------------------------------------------------------
1379 // A Logger is the interface used by logging modules to emit entries
1380 // to a log. A typical implementation will dump formatted data to a
1381 // sequence of files. We also provide interfaces that will forward
1382 // the data to another thread so that the invoker never blocks.
1383 // Implementations should be thread-safe since the logging system
1384 // will write to them from multiple threads.
1388 class GOOGLE_GLOG_DLL_DECL Logger {
1392 // Writes "message[0,message_len-1]" corresponding to an event that
1393 // occurred at "timestamp". If "force_flush" is true, the log file
1394 // is flushed immediately.
1396 // The input message has already been formatted as deemed
1397 // appropriate by the higher level logging facility. For example,
1398 // textual log messages already contain timestamps, and the
1399 // file:linenumber header.
1400 virtual void Write(bool force_flush,
1402 const char* message,
1403 int message_len) = 0;
1405 // Flush any buffered messages
1406 virtual void Flush() = 0;
1408 // Get the current LOG file size.
1409 // The returned value is approximate since some
1410 // logged data may not have been flushed to disk yet.
1411 virtual uint32 LogSize() = 0;
1414 // Get the logger for the specified severity level. The logger
1415 // remains the property of the logging module and should not be
1416 // deleted by the caller. Thread-safe.
1417 extern GOOGLE_GLOG_DLL_DECL Logger* GetLogger(LogSeverity level);
1419 // Set the logger for the specified severity level. The logger
1420 // becomes the property of the logging module and should not
1421 // be deleted by the caller. Thread-safe.
1422 extern GOOGLE_GLOG_DLL_DECL void SetLogger(LogSeverity level, Logger* logger);
1426 // glibc has traditionally implemented two incompatible versions of
1427 // strerror_r(). There is a poorly defined convention for picking the
1428 // version that we want, but it is not clear whether it even works with
1429 // all versions of glibc.
1430 // So, instead, we provide this wrapper that automatically detects the
1431 // version that is in use, and then implements POSIX semantics.
1432 // N.B. In addition to what POSIX says, we also guarantee that "buf" will
1433 // be set to an empty string, if this function failed. This means, in most
1434 // cases, you do not need to check the error code and you can directly
1435 // use the value of "buf". It will never have an undefined value.
1436 GOOGLE_GLOG_DLL_DECL int posix_strerror_r(int err, char *buf, size_t len);
1439 // A class for which we define operator<<, which does nothing.
1440 class GOOGLE_GLOG_DLL_DECL NullStream : public LogMessage::LogStream {
1442 // Initialize the LogStream so the messages can be written somewhere
1443 // (they'll never be actually displayed). This will be needed if a
1444 // NullStream& is implicitly converted to LogStream&, in which case
1445 // the overloaded NullStream::operator<< will not be invoked.
1446 NullStream() : LogMessage::LogStream(message_buffer_, 1, 0) { }
1447 NullStream(const char* /*file*/, int /*line*/,
1448 const CheckOpString& /*result*/) :
1449 LogMessage::LogStream(message_buffer_, 1, 0) { }
1450 NullStream &stream() { return *this; }
1452 // A very short buffer for messages (which we discard anyway). This
1453 // will be needed if NullStream& converted to LogStream& (e.g. as a
1454 // result of a conditional expression).
1455 char message_buffer_[2];
1458 // Do nothing. This operator is inline, allowing the message to be
1459 // compiled away. The message will not be compiled away if we do
1460 // something like (flag ? LOG(INFO) : LOG(ERROR)) << message; when
1461 // SKIP_LOG=WARNING. In those cases, NullStream will be implicitly
1462 // converted to LogStream and the message will be computed and then
1463 // quietly discarded.
1465 inline NullStream& operator<<(NullStream &str, const T &value) { return str; }
1467 // Similar to NullStream, but aborts the program (without stack
1468 // trace), like LogMessageFatal.
1469 class GOOGLE_GLOG_DLL_DECL NullStreamFatal : public NullStream {
1471 NullStreamFatal() { }
1472 NullStreamFatal(const char* file, int line, const CheckOpString& result) :
1473 NullStream(file, line, result) { }
1474 ~NullStreamFatal() { _exit(1); }
1477 // Install a signal handler that will dump signal information and a stack
1478 // trace when the program crashes on certain signals. We'll install the
1479 // signal handler for the following signals.
1481 // SIGSEGV, SIGILL, SIGFPE, SIGABRT, SIGBUS, and SIGTERM.
1483 // By default, the signal handler will write the failure dump to the
1484 // standard error. You can customize the destination by installing your
1485 // own writer function by InstallFailureWriter() below.
1487 // Note on threading:
1489 // The function should be called before threads are created, if you want
1490 // to use the failure signal handler for all threads. The stack trace
1491 // will be shown only for the thread that receives the signal. In other
1492 // words, stack traces of other threads won't be shown.
1493 GOOGLE_GLOG_DLL_DECL void InstallFailureSignalHandler();
1495 // Installs a function that is used for writing the failure dump. "data"
1496 // is the pointer to the beginning of a message to be written, and "size"
1497 // is the size of the message. You should not expect the data is
1498 // terminated with '\0'.
1499 GOOGLE_GLOG_DLL_DECL void InstallFailureWriter(
1500 void (*writer)(const char* data, int size));
1504 #endif // _LOGGING_H_