607ec1f7f3b55b195d61ad7ba6ac714439c9faf6
[platform/upstream/glog.git] / src / glog / logging.h.in
1 //
2 // Copyright (C) 1999 and onwards Google, Inc.
3 //
4 // Author: Ray Sidney
5 //
6 // This file contains #include information about logging-related stuff.
7 // Pretty much everybody needs to #include this file so that they can
8 // log various happenings.
9 //
10 #ifndef _LOGGING_H_
11 #define _LOGGING_H_
12
13 #include <errno.h>
14 #include <string.h>
15 #include <time.h>
16 #include <string>
17 #if @ac_cv_have_unistd_h@
18 # include <unistd.h>
19 #endif
20 #ifdef __DEPRECATED
21 // Make GCC quiet.
22 # undef __DEPRECATED
23 # include <strstream>
24 # define __DEPRECATED
25 #else
26 # include <strstream>
27 #endif
28 #include <vector>
29
30 // Annoying stuff for windows -- makes sure clients can import these functions
31 #ifndef GOOGLE_GLOG_DLL_DECL
32 # if defined(_WIN32) && !defined(__CYGWIN__)
33 #   define GOOGLE_GLOG_DLL_DECL  __declspec(dllimport)
34 # else
35 #   define GOOGLE_GLOG_DLL_DECL
36 # endif
37 #endif
38
39 // We care a lot about number of bits things take up.  Unfortunately,
40 // systems define their bit-specific ints in a lot of different ways.
41 // We use our own way, and have a typedef to get there.
42 // Note: these commands below may look like "#if 1" or "#if 0", but
43 // that's because they were constructed that way at ./configure time.
44 // Look at logging.h.in to see how they're calculated (based on your config).
45 #if @ac_cv_have_stdint_h@
46 #include <stdint.h>             // the normal place uint16_t is defined
47 #endif
48 #if @ac_cv_have_systypes_h@
49 #include <sys/types.h>          // the normal place u_int16_t is defined
50 #endif
51 #if @ac_cv_have_inttypes_h@
52 #include <inttypes.h>           // a third place for uint16_t or u_int16_t
53 #endif
54
55 #if @ac_cv_have_libgflags@
56 #include <gflags/gflags.h>
57 #endif
58
59 @ac_google_start_namespace@
60
61 #if @ac_cv_have_uint16_t@      // the C99 format
62 typedef int32_t int32;
63 typedef uint32_t uint32;
64 typedef int64_t int64;
65 typedef uint64_t uint64;
66 #elif @ac_cv_have_u_int16_t@   // the BSD format
67 typedef int32_t int32;
68 typedef u_int32_t uint32;
69 typedef int64_t int64;
70 typedef u_int64_t uint64;
71 #elif @ac_cv_have___uint16@    // the windows (vc7) format
72 typedef __int32 int32;
73 typedef unsigned __int32 uint32;
74 typedef __int64 int64;
75 typedef unsigned __int64 uint64;
76 #else
77 #error Do not know how to define a 32-bit integer quantity on your system
78 #endif
79
80 @ac_google_end_namespace@
81
82 // The global value of GOOGLE_STRIP_LOG. All the messages logged to
83 // LOG(XXX) with severity less than GOOGLE_STRIP_LOG will not be displayed.
84 // If it can be determined at compile time that the message will not be
85 // printed, the statement will be compiled out.
86 //
87 // Example: to strip out all INFO and WARNING messages, use the value
88 // of 2 below. To make an exception for WARNING messages from a single
89 // file, add "#define GOOGLE_STRIP_LOG 1" to that file _before_ including
90 // base/logging.h
91 #ifndef GOOGLE_STRIP_LOG
92 #define GOOGLE_STRIP_LOG 0
93 #endif
94
95 // GCC can be told that a certain branch is not likely to be taken (for
96 // instance, a CHECK failure), and use that information in static analysis.
97 // Giving it this information can help it optimize for the common case in
98 // the absence of better information (ie. -fprofile-arcs).
99 //
100 #ifndef GOOGLE_PREDICT_BRANCH_NOT_TAKEN
101 #if @ac_cv_have___builtin_expect@
102 #define GOOGLE_PREDICT_BRANCH_NOT_TAKEN(x) (__builtin_expect(x, 0))
103 #else
104 #define GOOGLE_PREDICT_BRANCH_NOT_TAKEN(x) x
105 #endif
106 #endif
107
108 // Make a bunch of macros for logging.  The way to log things is to stream
109 // things to LOG(<a particular severity level>).  E.g.,
110 //
111 //   LOG(INFO) << "Found " << num_cookies << " cookies";
112 //
113 // You can capture log messages in a string, rather than reporting them
114 // immediately:
115 //
116 //   vector<string> errors;
117 //   LOG_STRING(ERROR, &errors) << "Couldn't parse cookie #" << cookie_num;
118 //
119 // This pushes back the new error onto 'errors'; if given a NULL pointer,
120 // it reports the error via LOG(ERROR).
121 //
122 // You can also do conditional logging:
123 //
124 //   LOG_IF(INFO, num_cookies > 10) << "Got lots of cookies";
125 //
126 // You can also do occasional logging (log every n'th occurrence of an
127 // event):
128 //
129 //   LOG_EVERY_N(INFO, 10) << "Got the " << COUNTER << "th cookie";
130 //
131 // The above will cause log messages to be output on the 1st, 11th, 21st, ...
132 // times it is executed.  Note that the special COUNTER value is used to
133 // identify which repetition is happening.
134 //
135 // You can also do occasional conditional logging (log every n'th
136 // occurrence of an event, when condition is satisfied):
137 //
138 //   LOG_IF_EVERY_N(INFO, (size > 1024), 10) << "Got the " << COUNTER
139 //                                           << "th big cookie";
140 //
141 // You can log messages the first N times your code executes a line. E.g.
142 //
143 //   LOG_FIRST_N(INFO, 20) << "Got the " << COUNTER << "th cookie";
144 //
145 // Outputs log messages for the first 20 times it is executed.
146 //
147 // Analogous SYSLOG, SYSLOG_IF, and SYSLOG_EVERY_N macros are available.
148 // These log to syslog as well as to the normal logs.  If you use these at
149 // all, you need to be aware that syslog can drastically reduce performance,
150 // especially if it is configured for remote logging!  Don't use these
151 // unless you fully understand this and have a concrete need to use them.
152 // Even then, try to minimize your use of them.
153 //
154 // There are also "debug mode" logging macros like the ones above:
155 //
156 //   DLOG(INFO) << "Found cookies";
157 //
158 //   DLOG_IF(INFO, num_cookies > 10) << "Got lots of cookies";
159 //
160 //   DLOG_EVERY_N(INFO, 10) << "Got the " << COUNTER << "th cookie";
161 //
162 // All "debug mode" logging is compiled away to nothing for non-debug mode
163 // compiles.
164 //
165 // We also have
166 //
167 //   LOG_ASSERT(assertion);
168 //   DLOG_ASSERT(assertion);
169 //
170 // which is syntactic sugar for {,D}LOG_IF(FATAL, assert fails) << assertion;
171 //
172 // There are "verbose level" logging macros.  They look like
173 //
174 //   VLOG(1) << "I'm printed when you run the program with --v=1 or more";
175 //   VLOG(2) << "I'm printed when you run the program with --v=2 or more";
176 //
177 // These always log at the INFO log level (when they log at all).
178 // The verbose logging can also be turned on module-by-module.  For instance,
179 //    --vmodule=mapreduce=2,file=1,gfs*=3 --v=0
180 // will cause:
181 //   a. VLOG(2) and lower messages to be printed from mapreduce.{h,cc}
182 //   b. VLOG(1) and lower messages to be printed from file.{h,cc}
183 //   c. VLOG(3) and lower messages to be printed from files prefixed with "gfs"
184 //   d. VLOG(0) and lower messages to be printed from elsewhere
185 //
186 // The wildcarding functionality shown by (c) supports both '*' (match
187 // 0 or more characters) and '?' (match any single character) wildcards.
188 //
189 // There's also VLOG_IS_ON(n) "verbose level" condition macro. To be used as
190 //
191 //   if (VLOG_IS_ON(2)) {
192 //     // do some logging preparation and logging
193 //     // that can't be accomplished with just VLOG(2) << ...;
194 //   }
195 //
196 // There are also VLOG_IF, VLOG_EVERY_N and VLOG_IF_EVERY_N "verbose level"
197 // condition macros for sample cases, when some extra computation and
198 // preparation for logs is not needed.
199 //   VLOG_IF(1, (size > 1024))
200 //      << "I'm printed when size is more than 1024 and when you run the "
201 //         "program with --v=1 or more";
202 //   VLOG_EVERY_N(1, 10)
203 //      << "I'm printed every 10th occurrence, and when you run the program "
204 //         "with --v=1 or more. Present occurence is " << COUNTER;
205 //   VLOG_IF_EVERY_N(1, (size > 1024), 10)
206 //      << "I'm printed on every 10th occurence of case when size is more "
207 //         " than 1024, when you run the program with --v=1 or more. ";
208 //         "Present occurence is " << COUNTER;
209 //
210 // The supported severity levels for macros that allow you to specify one
211 // are (in increasing order of severity) INFO, WARNING, ERROR, and FATAL.
212 // Note that messages of a given severity are logged not only in the
213 // logfile for that severity, but also in all logfiles of lower severity.
214 // E.g., a message of severity FATAL will be logged to the logfiles of
215 // severity FATAL, ERROR, WARNING, and INFO.
216 //
217 // There is also the special severity of DFATAL, which logs FATAL in
218 // debug mode, ERROR in normal mode.
219 //
220 // Very important: logging a message at the FATAL severity level causes
221 // the program to terminate (after the message is logged).
222 //
223 // Unless otherwise specified, logs will be written to the filename
224 // "<program name>.<hostname>.<user name>.log.<severity level>.", followed
225 // by the date, time, and pid (you can't prevent the date, time, and pid
226 // from being in the filename).
227 //
228 // The logging code takes two flags:
229 //     --v=#           set the verbose level
230 //     --logtostderr   log all the messages to stderr instead of to logfiles
231
232 // LOG LINE PREFIX FORMAT
233 //
234 // Log lines have this form:
235 //
236 //     Lmmdd hh:mm:ss.uuuuuu threadid file:line] msg...
237 //
238 // where the fields are defined as follows:
239 //
240 //   L                A single character, representing the log level
241 //                    (eg 'I' for INFO)
242 //   mm               The month (zero padded; ie May is '05')
243 //   dd               The day (zero padded)
244 //   hh:mm:ss.uuuuuu  Time in hours, minutes and fractional seconds
245 //   threadid         The space-padded thread ID as returned by GetTID()
246 //                    (this matches the PID on Linux)
247 //   file             The file name
248 //   line             The line number
249 //   msg              The user-supplied message
250 //
251 // Example:
252 //
253 //   I1103 11:57:31.739339 24395 google.cc:2341] Command line: ./some_prog
254 //   I1103 11:57:31.739403 24395 google.cc:2342] Process id 24395
255 //
256 // NOTE: although the microseconds are useful for comparing events on
257 // a single machine, clocks on different machines may not be well
258 // synchronized.  Hence, use caution when comparing the low bits of
259 // timestamps from different machines.
260
261 #ifndef DECLARE_VARIABLE
262 #define MUST_UNDEF_GFLAGS_DECLARE_MACROS
263 #define DECLARE_VARIABLE(type, name, tn)                                      \
264   namespace FLAG__namespace_do_not_use_directly_use_DECLARE_##tn##_instead {  \
265   extern GOOGLE_GLOG_DLL_DECL type FLAGS_##name;                              \
266   }                                                                           \
267   using FLAG__namespace_do_not_use_directly_use_DECLARE_##tn##_instead::FLAGS_##name
268
269 // bool specialization
270 #define DECLARE_bool(name) \
271   DECLARE_VARIABLE(bool, name, bool)
272
273 // int32 specialization
274 #define DECLARE_int32(name) \
275   DECLARE_VARIABLE(@ac_google_namespace@::int32, name, int32)
276
277 // Special case for string, because we have to specify the namespace
278 // std::string, which doesn't play nicely with our FLAG__namespace hackery.
279 #define DECLARE_string(name)                                          \
280   namespace FLAG__namespace_do_not_use_directly_use_DECLARE_string_instead {  \
281   extern GOOGLE_GLOG_DLL_DECL std::string FLAGS_##name;                       \
282   }                                                                           \
283   using FLAG__namespace_do_not_use_directly_use_DECLARE_string_instead::FLAGS_##name
284 #endif
285
286 // Set whether log messages go to stderr instead of logfiles
287 DECLARE_bool(logtostderr);
288
289 // Set whether log messages go to stderr in addition to logfiles.
290 DECLARE_bool(alsologtostderr);
291
292 // Log messages at a level >= this flag are automatically sent to
293 // stderr in addition to log files.
294 DECLARE_int32(stderrthreshold);
295
296 // Set whether the log prefix should be prepended to each line of output.
297 DECLARE_bool(log_prefix);
298
299 // Log messages at a level <= this flag are buffered.
300 // Log messages at a higher level are flushed immediately.
301 DECLARE_int32(logbuflevel);
302
303 // Sets the maximum number of seconds which logs may be buffered for.
304 DECLARE_int32(logbufsecs);
305
306 // Log suppression level: messages logged at a lower level than this
307 // are suppressed.
308 DECLARE_int32(minloglevel);
309
310 // If specified, logfiles are written into this directory instead of the
311 // default logging directory.
312 DECLARE_string(log_dir);
313
314 // Sets the path of the directory into which to put additional links
315 // to the log files.
316 DECLARE_string(log_link);
317
318 DECLARE_int32(v);  // in vlog_is_on.cc
319
320 // Sets the maximum log file size (in MB).
321 DECLARE_int32(max_log_size);
322
323 // Sets whether to avoid logging to the disk if the disk is full.
324 DECLARE_bool(stop_logging_if_full_disk);
325
326 #ifdef MUST_UNDEF_GFLAGS_DECLARE_MACROS
327 #undef MUST_UNDEF_GFLAGS_DECLARE_MACROS
328 #undef DECLARE_VARIABLE
329 #undef DECLARE_bool
330 #undef DECLARE_int32
331 #undef DECLARE_string
332 #endif
333
334 // Log messages below the GOOGLE_STRIP_LOG level will be compiled away for
335 // security reasons. See LOG(severtiy) below.
336
337 // A few definitions of macros that don't generate much code.  Since
338 // LOG(INFO) and its ilk are used all over our code, it's
339 // better to have compact code for these operations.
340
341 #if GOOGLE_STRIP_LOG == 0
342 #define COMPACT_GOOGLE_LOG_INFO @ac_google_namespace@::LogMessage( \
343       __FILE__, __LINE__)
344 #define LOG_TO_STRING_INFO(message) @ac_google_namespace@::LogMessage( \
345       __FILE__, __LINE__, @ac_google_namespace@::INFO, message)
346 #else
347 #define COMPACT_GOOGLE_LOG_INFO @ac_google_namespace@::NullStream()
348 #define LOG_TO_STRING_INFO(message) @ac_google_namespace@::NullStream()
349 #endif
350
351 #if GOOGLE_STRIP_LOG <= 1
352 #define COMPACT_GOOGLE_LOG_WARNING @ac_google_namespace@::LogMessage( \
353       __FILE__, __LINE__, @ac_google_namespace@::WARNING)
354 #define LOG_TO_STRING_WARNING(message) @ac_google_namespace@::LogMessage( \
355       __FILE__, __LINE__, @ac_google_namespace@::WARNING, message)
356 #else
357 #define COMPACT_GOOGLE_LOG_WARNING @ac_google_namespace@::NullStream()
358 #define LOG_TO_STRING_WARNING(message) @ac_google_namespace@::NullStream()
359 #endif
360
361 #if GOOGLE_STRIP_LOG <= 2
362 #define COMPACT_GOOGLE_LOG_ERROR @ac_google_namespace@::LogMessage( \
363       __FILE__, __LINE__, @ac_google_namespace@::ERROR)
364 #define LOG_TO_STRING_ERROR(message) @ac_google_namespace@::LogMessage( \
365       __FILE__, __LINE__, @ac_google_namespace@::ERROR, message)
366 #else
367 #define COMPACT_GOOGLE_LOG_ERROR @ac_google_namespace@::NullStream()
368 #define LOG_TO_STRING_ERROR(message) @ac_google_namespace@::NullStream()
369 #endif
370
371 #if GOOGLE_STRIP_LOG <= 3
372 #define COMPACT_GOOGLE_LOG_FATAL @ac_google_namespace@::LogMessageFatal( \
373       __FILE__, __LINE__)
374 #define LOG_TO_STRING_FATAL(message) @ac_google_namespace@::LogMessage( \
375       __FILE__, __LINE__, @ac_google_namespace@::FATAL, message)
376 #else
377 #define COMPACT_GOOGLE_LOG_FATAL @ac_google_namespace@::NullStreamFatal()
378 #define LOG_TO_STRING_FATAL(message) @ac_google_namespace@::NullStreamFatal()
379 #endif
380
381 // For DFATAL, we want to use LogMessage (as opposed to
382 // LogMessageFatal), to be consistent with the original behavior.
383 #ifdef NDEBUG
384 #define COMPACT_GOOGLE_LOG_DFATAL COMPACT_GOOGLE_LOG_ERROR
385 #elif GOOGLE_STRIP_LOG <= 3
386 #define COMPACT_GOOGLE_LOG_DFATAL LogMessage( \
387       __FILE__, __LINE__, @ac_google_namespace@::FATAL)
388 #else
389 #define COMPACT_GOOGLE_LOG_DFATAL @ac_google_namespace@::NullStreamFatal()
390 #endif
391
392 #define GOOGLE_LOG_INFO(counter) @ac_google_namespace@::LogMessage(__FILE__, __LINE__, @ac_google_namespace@::INFO, counter, &@ac_google_namespace@::LogMessage::SendToLog)
393 #define SYSLOG_INFO(counter) \
394   @ac_google_namespace@::LogMessage(__FILE__, __LINE__, @ac_google_namespace@::INFO, counter, \
395   &@ac_google_namespace@::LogMessage::SendToSyslogAndLog)
396 #define GOOGLE_LOG_WARNING(counter)  \
397   @ac_google_namespace@::LogMessage(__FILE__, __LINE__, @ac_google_namespace@::WARNING, counter, \
398   &@ac_google_namespace@::LogMessage::SendToLog)
399 #define SYSLOG_WARNING(counter)  \
400   @ac_google_namespace@::LogMessage(__FILE__, __LINE__, @ac_google_namespace@::WARNING, counter, \
401   &@ac_google_namespace@::LogMessage::SendToSyslogAndLog)
402 #define GOOGLE_LOG_ERROR(counter)  \
403   @ac_google_namespace@::LogMessage(__FILE__, __LINE__, @ac_google_namespace@::ERROR, counter, \
404   &@ac_google_namespace@::LogMessage::SendToLog)
405 #define SYSLOG_ERROR(counter)  \
406   @ac_google_namespace@::LogMessage(__FILE__, __LINE__, @ac_google_namespace@::ERROR, counter, \
407   &@ac_google_namespace@::LogMessage::SendToSyslogAndLog)
408 #define GOOGLE_LOG_FATAL(counter) \
409   @ac_google_namespace@::LogMessage(__FILE__, __LINE__, @ac_google_namespace@::FATAL, counter, \
410   &@ac_google_namespace@::LogMessage::SendToLog)
411 #define SYSLOG_FATAL(counter) \
412   @ac_google_namespace@::LogMessage(__FILE__, __LINE__, @ac_google_namespace@::FATAL, counter, \
413   &@ac_google_namespace@::LogMessage::SendToSyslogAndLog)
414 #define GOOGLE_LOG_DFATAL(counter) \
415   @ac_google_namespace@::LogMessage(__FILE__, __LINE__, @ac_google_namespace@::DFATAL_LEVEL, counter, \
416   &@ac_google_namespace@::LogMessage::SendToLog)
417 #define SYSLOG_DFATAL(counter) \
418   @ac_google_namespace@::LogMessage(__FILE__, __LINE__, @ac_google_namespace@::DFATAL_LEVEL, counter, \
419   &@ac_google_namespace@::LogMessage::SendToSyslogAndLog)
420
421 #if defined(WIN32) || defined(_WIN32) || defined(__WIN32__) || defined(__CYGWIN__) || defined(__CYGWIN32__)
422 // A very useful logging macro to log windows errors:
423 #define LOG_SYSRESULT(result) \
424   if (FAILED(result)) { \
425     LPTSTR message = NULL; \
426     LPTSTR msg = reinterpret_cast<LPTSTR>(&message); \
427     DWORD message_length = FormatMessage(FORMAT_MESSAGE_ALLOCATE_BUFFER | \
428                          FORMAT_MESSAGE_FROM_SYSTEM, \
429                          0, result, 0, msg, 100, NULL); \
430     if (message_length > 0) { \
431       @ac_google_namespace@::LogMessage(__FILE__, __LINE__, ERROR, 0, \
432           &@ac_google_namespace@::LogMessage::SendToLog).stream() << message; \
433       LocalFree(message); \
434     } \
435   }
436 #endif
437
438 // We use the preprocessor's merging operator, "##", so that, e.g.,
439 // LOG(INFO) becomes the token GOOGLE_LOG_INFO.  There's some funny
440 // subtle difference between ostream member streaming functions (e.g.,
441 // ostream::operator<<(int) and ostream non-member streaming functions
442 // (e.g., ::operator<<(ostream&, string&): it turns out that it's
443 // impossible to stream something like a string directly to an unnamed
444 // ostream. We employ a neat hack by calling the stream() member
445 // function of LogMessage which seems to avoid the problem.
446 #define LOG(severity) COMPACT_GOOGLE_LOG_ ## severity.stream()
447 #define SYSLOG(severity) SYSLOG_ ## severity(0).stream()
448
449 @ac_google_start_namespace@
450
451 // They need the definitions of integer types.
452 #include "glog/log_severity.h"
453 #include "glog/vlog_is_on.h"
454
455 // Initialize google's logging library. You will see the program name
456 // specified by argv0 in log outputs.
457 GOOGLE_GLOG_DLL_DECL void InitGoogleLogging(const char* argv0);
458
459 // Install a function which will be called after LOG(FATAL).
460 GOOGLE_GLOG_DLL_DECL void InstallFailureFunction(void (*fail_func)());
461
462 class LogSink;  // defined below
463
464 // If a non-NULL sink pointer is given, we push this message to that sink.
465 // For LOG_TO_SINK we then do normal LOG(severity) logging as well.
466 // This is useful for capturing messages and passing/storing them
467 // somewhere more specific than the global log of the process.
468 // Argument types:
469 //   LogSink* sink;
470 //   LogSeverity severity;
471 // The cast is to disambiguate NULL arguments.
472 #define LOG_TO_SINK(sink, severity) \
473   @ac_google_namespace@::LogMessage(                                    \
474       __FILE__, __LINE__,                                               \
475       @ac_google_namespace@::severity,                                  \
476       static_cast<@ac_google_namespace@::LogSink*>(sink), true).stream()
477 #define LOG_TO_SINK_BUT_NOT_TO_LOGFILE(sink, severity)                  \
478   @ac_google_namespace@::LogMessage(                                    \
479       __FILE__, __LINE__,                                               \
480       @ac_google_namespace@::severity,                                  \
481       static_cast<@ac_google_namespace@::LogSink*>(sink), false).stream()
482
483 // If a non-NULL string pointer is given, we write this message to that string.
484 // We then do normal LOG(severity) logging as well.
485 // This is useful for capturing messages and storing them somewhere more
486 // specific than the global log of the process.
487 // Argument types:
488 //   string* message;
489 //   LogSeverity severity;
490 // The cast is to disambiguate NULL arguments.
491 // NOTE: LOG(severity) expands to LogMessage().stream() for the specified
492 // severity.
493 #define LOG_TO_STRING(severity, message) \
494   LOG_TO_STRING_##severity(static_cast<string*>(message)).stream()
495
496 // If a non-NULL pointer is given, we push the message onto the end
497 // of a vector of strings; otherwise, we report it with LOG(severity).
498 // This is handy for capturing messages and perhaps passing them back
499 // to the caller, rather than reporting them immediately.
500 // Argument types:
501 //   LogSeverity severity;
502 //   vector<string> *outvec;
503 // The cast is to disambiguate NULL arguments.
504 #define LOG_STRING(severity, outvec) \
505   LOG_TO_STRING_##severity(static_cast<vector<string>*>(outvec)).stream()
506
507 #define LOG_IF(severity, condition) \
508   !(condition) ? (void) 0 : @ac_google_namespace@::LogMessageVoidify() & LOG(severity)
509 #define SYSLOG_IF(severity, condition) \
510   !(condition) ? (void) 0 : @ac_google_namespace@::LogMessageVoidify() & SYSLOG(severity)
511
512 #define LOG_ASSERT(condition)  \
513   LOG_IF(FATAL, !(condition)) << "Assert failed: " #condition
514 #define SYSLOG_ASSERT(condition) \
515   SYSLOG_IF(FATAL, !(condition)) << "Assert failed: " #condition
516
517 // CHECK dies with a fatal error if condition is not true.  It is *not*
518 // controlled by NDEBUG, so the check will be executed regardless of
519 // compilation mode.  Therefore, it is safe to do things like:
520 //    CHECK(fp->Write(x) == 4)
521 #define CHECK(condition)  \
522       LOG_IF(FATAL, GOOGLE_PREDICT_BRANCH_NOT_TAKEN(!(condition))) \
523              << "Check failed: " #condition " "
524
525 // A container for a string pointer which can be evaluated to a bool -
526 // true iff the pointer is NULL.
527 struct CheckOpString {
528   CheckOpString(std::string* str) : str_(str) { }
529   // No destructor: if str_ is non-NULL, we're about to LOG(FATAL),
530   // so there's no point in cleaning up str_.
531   operator bool() const {
532     return GOOGLE_PREDICT_BRANCH_NOT_TAKEN(str_ != NULL);
533   }
534   std::string* str_;
535 };
536
537 // Function is overloaded for integral types to allow static const
538 // integrals declared in classes and not defined to be used as arguments to
539 // CHECK* macros. It's not encouraged though.
540 template <class T>
541 inline const T&       GetReferenceableValue(const T&           t) { return t; }
542 inline char           GetReferenceableValue(char               t) { return t; }
543 inline unsigned char  GetReferenceableValue(unsigned char      t) { return t; }
544 inline signed char    GetReferenceableValue(signed char        t) { return t; }
545 inline short          GetReferenceableValue(short              t) { return t; }
546 inline unsigned short GetReferenceableValue(unsigned short     t) { return t; }
547 inline int            GetReferenceableValue(int                t) { return t; }
548 inline unsigned int   GetReferenceableValue(unsigned int       t) { return t; }
549 inline long           GetReferenceableValue(long               t) { return t; }
550 inline unsigned long  GetReferenceableValue(unsigned long      t) { return t; }
551 inline long long      GetReferenceableValue(long long          t) { return t; }
552 inline unsigned long long GetReferenceableValue(unsigned long long t) {
553   return t;
554 }
555
556 // This is a dummy class to define the following operator.
557 struct DummyClassToDefineOperator {};
558
559 @ac_google_end_namespace@
560
561 // Define global operator<< to declare using ::operator<<.
562 // This declaration will allow use to use CHECK macros for user
563 // defined classes which have operator<< (e.g., stl_logging.h).
564 inline std::ostream& operator<<(
565     std::ostream& out, const google::DummyClassToDefineOperator& dummy) {
566   return out;
567 }
568
569 @ac_google_start_namespace@
570
571 // Build the error message string.
572 template<class t1, class t2>
573 std::string* MakeCheckOpString(const t1& v1, const t2& v2, const char* names) {
574   // It means that we cannot use stl_logging if compiler doesn't
575   // support using expression for operator.
576   // TODO(hamaji): Figure out a way to fix.
577 #if @ac_cv_cxx_using_operator@
578   using ::operator<<;
579 #endif
580   std::strstream ss;
581   ss << names << " (" << v1 << " vs. " << v2 << ")";
582   return new std::string(ss.str(), ss.pcount());
583 }
584
585 // Helper functions for CHECK_OP macro.
586 // The (int, int) specialization works around the issue that the compiler
587 // will not instantiate the template version of the function on values of
588 // unnamed enum type - see comment below.
589 #define DEFINE_CHECK_OP_IMPL(name, op) \
590   template <class t1, class t2> \
591   inline std::string* Check##name##Impl(const t1& v1, const t2& v2, \
592                                         const char* names) { \
593     if (v1 op v2) return NULL; \
594     else return MakeCheckOpString(v1, v2, names); \
595   } \
596   inline std::string* Check##name##Impl(int v1, int v2, const char* names) { \
597     return Check##name##Impl<int, int>(v1, v2, names); \
598   }
599
600 // Use _EQ, _NE, _LE, etc. in case the file including base/logging.h
601 // provides its own #defines for the simpler names EQ, NE, LE, etc.
602 // This happens if, for example, those are used as token names in a
603 // yacc grammar.
604 DEFINE_CHECK_OP_IMPL(_EQ, ==)
605 DEFINE_CHECK_OP_IMPL(_NE, !=)
606 DEFINE_CHECK_OP_IMPL(_LE, <=)
607 DEFINE_CHECK_OP_IMPL(_LT, < )
608 DEFINE_CHECK_OP_IMPL(_GE, >=)
609 DEFINE_CHECK_OP_IMPL(_GT, > )
610 #undef DEFINE_CHECK_OP_IMPL
611
612 // Helper macro for binary operators.
613 // Don't use this macro directly in your code, use CHECK_EQ et al below.
614
615 #if defined(STATIC_ANALYSIS)
616 // Only for static analysis tool to know that it is equivalent to assert
617 #define CHECK_OP_LOG(name, op, val1, val2, log) CHECK((val1) op (val2))
618 #elif !defined(NDEBUG)
619 // In debug mode, avoid constructing CheckOpStrings if possible,
620 // to reduce the overhead of CHECK statments by 2x.
621 // Real DCHECK-heavy tests have seen 1.5x speedups.
622
623 // The meaning of "string" might be different between now and 
624 // when this macro gets invoked (e.g., if someone is experimenting
625 // with other string implementations that get defined after this
626 // file is included).  Save the current meaning now and use it 
627 // in the macro.
628 typedef std::string _Check_string;
629 #define CHECK_OP_LOG(name, op, val1, val2, log) \
630   while (@ac_google_namespace@::_Check_string* _result =                \
631          @ac_google_namespace@::Check##name##Impl(                      \
632              @ac_google_namespace@::GetReferenceableValue(val1),        \
633              @ac_google_namespace@::GetReferenceableValue(val2),        \
634              #val1 " " #op " " #val2))                                  \
635     log(__FILE__, __LINE__,                                             \
636         @ac_google_namespace@::CheckOpString(_result)).stream()
637 #else
638 // In optimized mode, use CheckOpString to hint to compiler that
639 // the while condition is unlikely.
640 #define CHECK_OP_LOG(name, op, val1, val2, log) \
641   while (@ac_google_namespace@::CheckOpString _result = \
642          @ac_google_namespace@::Check##name##Impl(GetReferenceableValue(val1), \
643                            GetReferenceableValue(val2), \
644                            #val1 " " #op " " #val2)) \
645     log(__FILE__, __LINE__, _result).stream()
646 #endif  // STATIC_ANALYSIS, !NDEBUG
647
648 #if GOOGLE_STRIP_LOG <= 3
649 #define CHECK_OP(name, op, val1, val2) \
650   CHECK_OP_LOG(name, op, val1, val2, @ac_google_namespace@::LogMessageFatal)
651 #else
652 #define CHECK_OP(name, op, val1, val2) \
653   CHECK_OP_LOG(name, op, val1, val2, @ac_google_namespace@::NullStreamFatal)
654 #endif // STRIP_LOG <= 3
655
656 // Equality/Inequality checks - compare two values, and log a FATAL message
657 // including the two values when the result is not as expected.  The values
658 // must have operator<<(ostream, ...) defined.
659 //
660 // You may append to the error message like so:
661 //   CHECK_NE(1, 2) << ": The world must be ending!";
662 //
663 // We are very careful to ensure that each argument is evaluated exactly
664 // once, and that anything which is legal to pass as a function argument is
665 // legal here.  In particular, the arguments may be temporary expressions
666 // which will end up being destroyed at the end of the apparent statement,
667 // for example:
668 //   CHECK_EQ(string("abc")[1], 'b');
669 //
670 // WARNING: These don't compile correctly if one of the arguments is a pointer
671 // and the other is NULL. To work around this, simply static_cast NULL to the
672 // type of the desired pointer.
673
674 #define CHECK_EQ(val1, val2) CHECK_OP(_EQ, ==, val1, val2)
675 #define CHECK_NE(val1, val2) CHECK_OP(_NE, !=, val1, val2)
676 #define CHECK_LE(val1, val2) CHECK_OP(_LE, <=, val1, val2)
677 #define CHECK_LT(val1, val2) CHECK_OP(_LT, < , val1, val2)
678 #define CHECK_GE(val1, val2) CHECK_OP(_GE, >=, val1, val2)
679 #define CHECK_GT(val1, val2) CHECK_OP(_GT, > , val1, val2)
680
681 // Check that the input is non NULL.  This very useful in constructor
682 // initializer lists.
683
684 #define CHECK_NOTNULL(val) \
685   @ac_google_namespace@::CheckNotNull(__FILE__, __LINE__, "'" #val "' Must be non NULL", (val))
686
687 // Helper functions for string comparisons.
688 // To avoid bloat, the definitions are in logging.cc.
689 #define DECLARE_CHECK_STROP_IMPL(func, expected) \
690   GOOGLE_GLOG_DLL_DECL std::string* Check##func##expected##Impl( \
691       const char* s1, const char* s2, const char* names);
692 DECLARE_CHECK_STROP_IMPL(strcmp, true)
693 DECLARE_CHECK_STROP_IMPL(strcmp, false)
694 DECLARE_CHECK_STROP_IMPL(strcasecmp, true)
695 DECLARE_CHECK_STROP_IMPL(strcasecmp, false)
696 #undef DECLARE_CHECK_STROP_IMPL
697
698 // Helper macro for string comparisons.
699 // Don't use this macro directly in your code, use CHECK_STREQ et al below.
700 #define CHECK_STROP(func, op, expected, s1, s2) \
701   while (@ac_google_namespace@::CheckOpString _result = \
702          @ac_google_namespace@::Check##func##expected##Impl((s1), (s2), \
703                                      #s1 " " #op " " #s2)) \
704     LOG(FATAL) << *_result.str_
705
706
707 // String (char*) equality/inequality checks.
708 // CASE versions are case-insensitive.
709 //
710 // Note that "s1" and "s2" may be temporary strings which are destroyed
711 // by the compiler at the end of the current "full expression"
712 // (e.g. CHECK_STREQ(Foo().c_str(), Bar().c_str())).
713
714 #define CHECK_STREQ(s1, s2) CHECK_STROP(strcmp, ==, true, s1, s2)
715 #define CHECK_STRNE(s1, s2) CHECK_STROP(strcmp, !=, false, s1, s2)
716 #define CHECK_STRCASEEQ(s1, s2) CHECK_STROP(strcasecmp, ==, true, s1, s2)
717 #define CHECK_STRCASENE(s1, s2) CHECK_STROP(strcasecmp, !=, false, s1, s2)
718
719 #define CHECK_INDEX(I,A) CHECK(I < (sizeof(A)/sizeof(A[0])))
720 #define CHECK_BOUND(B,A) CHECK(B <= (sizeof(A)/sizeof(A[0])))
721
722 #define CHECK_DOUBLE_EQ(val1, val2)              \
723   do {                                           \
724     CHECK_LE((val1), (val2)+0.000000000000001L); \
725     CHECK_GE((val1), (val2)-0.000000000000001L); \
726   } while (0)
727
728 #define CHECK_NEAR(val1, val2, margin)           \
729   do {                                           \
730     CHECK_LE((val1), (val2)+(margin));           \
731     CHECK_GE((val1), (val2)-(margin));           \
732   } while (0)
733
734 // perror()..googly style!
735 //
736 // PLOG() and PLOG_IF() and PCHECK() behave exactly like their LOG* and
737 // CHECK equivalents with the addition that they postpend a description
738 // of the current state of errno to their output lines.
739
740 #define PLOG(severity) GOOGLE_PLOG(severity, 0).stream()
741
742 #define GOOGLE_PLOG(severity, counter)  \
743   @ac_google_namespace@::ErrnoLogMessage( \
744       __FILE__, __LINE__, @ac_google_namespace@::severity, counter, \
745       &@ac_google_namespace@::LogMessage::SendToLog)
746
747 #define PLOG_IF(severity, condition) \
748   !(condition) ? (void) 0 : @ac_google_namespace@::LogMessageVoidify() & PLOG(severity)
749
750 // A CHECK() macro that postpends errno if the condition is false. E.g.
751 //
752 // if (poll(fds, nfds, timeout) == -1) { PCHECK(errno == EINTR); ... }
753 #define PCHECK(condition)  \
754       PLOG_IF(FATAL, GOOGLE_PREDICT_BRANCH_NOT_TAKEN(!(condition))) \
755               << "Check failed: " #condition " "
756
757 // A CHECK() macro that lets you assert the success of a function that
758 // returns -1 and sets errno in case of an error. E.g.
759 //
760 // CHECK_ERR(mkdir(path, 0700));
761 //
762 // or
763 //
764 // int fd = open(filename, flags); CHECK_ERR(fd) << ": open " << filename;
765 #define CHECK_ERR(invocation)                                          \
766 PLOG_IF(FATAL, GOOGLE_PREDICT_BRANCH_NOT_TAKEN((invocation) == -1))    \
767         << #invocation
768
769 // Use macro expansion to create, for each use of LOG_EVERY_N(), static
770 // variables with the __LINE__ expansion as part of the variable name.
771 #define LOG_EVERY_N_VARNAME(base, line) LOG_EVERY_N_VARNAME_CONCAT(base, line)
772 #define LOG_EVERY_N_VARNAME_CONCAT(base, line) base ## line
773
774 #define LOG_OCCURRENCES LOG_EVERY_N_VARNAME(occurrences_, __LINE__)
775 #define LOG_OCCURRENCES_MOD_N LOG_EVERY_N_VARNAME(occurrences_mod_n_, __LINE__)
776
777 #define SOME_KIND_OF_LOG_EVERY_N(severity, n, what_to_do) \
778   static int LOG_OCCURRENCES = 0, LOG_OCCURRENCES_MOD_N = 0; \
779   ++LOG_OCCURRENCES; \
780   if (++LOG_OCCURRENCES_MOD_N > n) LOG_OCCURRENCES_MOD_N -= n; \
781   if (LOG_OCCURRENCES_MOD_N == 1) \
782     @ac_google_namespace@::LogMessage( \
783         __FILE__, __LINE__, @ac_google_namespace@::severity, LOG_OCCURRENCES, \
784         &what_to_do).stream()
785
786 #define SOME_KIND_OF_LOG_IF_EVERY_N(severity, condition, n, what_to_do) \
787   static int LOG_OCCURRENCES = 0, LOG_OCCURRENCES_MOD_N = 0; \
788   ++LOG_OCCURRENCES; \
789   if (condition && \
790       ((LOG_OCCURRENCES_MOD_N=(LOG_OCCURRENCES_MOD_N + 1) % n) == (1 % n))) \
791     @ac_google_namespace@::LogMessage( \
792         __FILE__, __LINE__, @ac_google_namespace@::severity, LOG_OCCURRENCES, \
793                  &what_to_do).stream()
794
795 #define SOME_KIND_OF_PLOG_EVERY_N(severity, n, what_to_do) \
796   static int LOG_OCCURRENCES = 0, LOG_OCCURRENCES_MOD_N = 0; \
797   ++LOG_OCCURRENCES; \
798   if (++LOG_OCCURRENCES_MOD_N > n) LOG_OCCURRENCES_MOD_N -= n; \
799   if (LOG_OCCURRENCES_MOD_N == 1) \
800     @ac_google_namespace@::ErrnoLogMessage( \
801         __FILE__, __LINE__, @ac_google_namespace@::severity, LOG_OCCURRENCES, \
802         &what_to_do).stream()
803
804 #define SOME_KIND_OF_LOG_FIRST_N(severity, n, what_to_do) \
805   static int LOG_OCCURRENCES = 0; \
806   if (LOG_OCCURRENCES <= n) \
807     ++LOG_OCCURRENCES; \
808   if (LOG_OCCURRENCES <= n) \
809     @ac_google_namespace@::LogMessage( \
810         __FILE__, __LINE__, @ac_google_namespace@::severity, LOG_OCCURRENCES, \
811         &what_to_do).stream()
812
813 namespace glog_internal_namespace_ {
814 template <bool>
815 struct CompileAssert {
816 };
817 }  // namespace glog_internal_namespace_
818
819 #define GOOGLE_GLOG_COMPILE_ASSERT(expr, msg) \
820   typedef @ac_google_namespace@::glog_internal_namespace_::CompileAssert<(bool(expr))> msg[bool(expr) ? 1 : -1]
821
822 #define LOG_EVERY_N(severity, n)                                        \
823   GOOGLE_GLOG_COMPILE_ASSERT(@ac_google_namespace@::severity <          \
824                              @ac_google_namespace@::NUM_SEVERITIES,     \
825                              INVALID_REQUESTED_LOG_SEVERITY);           \
826   SOME_KIND_OF_LOG_EVERY_N(severity, (n), @ac_google_namespace@::LogMessage::SendToLog)
827
828 #define SYSLOG_EVERY_N(severity, n) \
829   SOME_KIND_OF_LOG_EVERY_N(severity, (n), @ac_google_namespace@::LogMessage::SendToSyslogAndLog)
830
831 #define PLOG_EVERY_N(severity, n) \
832   SOME_KIND_OF_PLOG_EVERY_N(severity, (n), @ac_google_namespace@::LogMessage::SendToLog)
833
834 #define LOG_FIRST_N(severity, n) \
835   SOME_KIND_OF_LOG_FIRST_N(severity, (n), @ac_google_namespace@::LogMessage::SendToLog)
836
837 #define LOG_IF_EVERY_N(severity, condition, n) \
838   SOME_KIND_OF_LOG_IF_EVERY_N(severity, (condition), (n), @ac_google_namespace@::LogMessage::SendToLog)
839
840 // We want the special COUNTER value available for LOG_EVERY_X()'ed messages
841 enum PRIVATE_Counter {COUNTER};
842
843
844 // Plus some debug-logging macros that get compiled to nothing for production
845
846 #ifndef NDEBUG
847
848 #define DLOG(severity) LOG(severity)
849 #define DVLOG(verboselevel) VLOG(verboselevel)
850 #define DLOG_IF(severity, condition) LOG_IF(severity, condition)
851 #define DLOG_EVERY_N(severity, n) LOG_EVERY_N(severity, n)
852 #define DLOG_IF_EVERY_N(severity, condition, n) \
853   LOG_IF_EVERY_N(severity, condition, n)
854 #define DLOG_ASSERT(condition) LOG_ASSERT(condition)
855
856 // debug-only checking.  not executed in NDEBUG mode.
857 #define DCHECK(condition) CHECK(condition)
858 #define DCHECK_EQ(val1, val2) CHECK_EQ(val1, val2)
859 #define DCHECK_NE(val1, val2) CHECK_NE(val1, val2)
860 #define DCHECK_LE(val1, val2) CHECK_LE(val1, val2)
861 #define DCHECK_LT(val1, val2) CHECK_LT(val1, val2)
862 #define DCHECK_GE(val1, val2) CHECK_GE(val1, val2)
863 #define DCHECK_GT(val1, val2) CHECK_GT(val1, val2)
864 #define DCHECK_STREQ(str1, str2) CHECK_STREQ(str1, str2)
865 #define DCHECK_STRCASEEQ(str1, str2) CHECK_STRCASEEQ(str1, str2)
866 #define DCHECK_STRNE(str1, str2) CHECK_STRNE(str1, str2)
867 #define DCHECK_STRCASENE(str1, str2) CHECK_STRCASENE(str1, str2)
868
869 #else  // NDEBUG
870
871 #define DLOG(severity) \
872   true ? (void) 0 : @ac_google_namespace@::LogMessageVoidify() & LOG(severity)
873
874 #define DVLOG(verboselevel) \
875   (true || !VLOG_IS_ON(verboselevel)) ?\
876     (void) 0 : @ac_google_namespace@::LogMessageVoidify() & LOG(INFO)
877
878 #define DLOG_IF(severity, condition) \
879   (true || !(condition)) ? (void) 0 : @ac_google_namespace@::LogMessageVoidify() & LOG(severity)
880
881 #define DLOG_EVERY_N(severity, n) \
882   true ? (void) 0 : @ac_google_namespace@::LogMessageVoidify() & LOG(severity)
883
884 #define DLOG_IF_EVERY_N(severity, condition, n) \
885   (true || !(condition))? (void) 0 : @ac_google_namespace@::LogMessageVoidify() & LOG(severity)
886
887 #define DLOG_ASSERT(condition) \
888   true ? (void) 0 : LOG_ASSERT(condition)
889
890 #define DCHECK(condition) \
891   while (false) \
892     CHECK(condition)
893
894 #define DCHECK_EQ(val1, val2) \
895   while (false) \
896     CHECK_EQ(val1, val2)
897
898 #define DCHECK_NE(val1, val2) \
899   while (false) \
900     CHECK_NE(val1, val2)
901
902 #define DCHECK_LE(val1, val2) \
903   while (false) \
904     CHECK_LE(val1, val2)
905
906 #define DCHECK_LT(val1, val2) \
907   while (false) \
908     CHECK_LT(val1, val2)
909
910 #define DCHECK_GE(val1, val2) \
911   while (false) \
912     CHECK_GE(val1, val2)
913
914 #define DCHECK_GT(val1, val2) \
915   while (false) \
916     CHECK_GT(val1, val2)
917
918 #define DCHECK_STREQ(str1, str2) \
919   while (false) \
920     CHECK_STREQ(str1, str2)
921
922 #define DCHECK_STRCASEEQ(str1, str2) \
923   while (false) \
924     CHECK_STRCASEEQ(str1, str2)
925
926 #define DCHECK_STRNE(str1, str2) \
927   while (false) \
928     CHECK_STRNE(str1, str2)
929
930 #define DCHECK_STRCASENE(str1, str2) \
931   while (false) \
932     CHECK_STRCASENE(str1, str2)
933
934
935 #endif  // NDEBUG
936
937 // Log only in verbose mode.
938
939 #define VLOG(verboselevel) LOG_IF(INFO, VLOG_IS_ON(verboselevel))
940
941 #define VLOG_IF(verboselevel, condition) \
942   LOG_IF(INFO, (condition) && VLOG_IS_ON(verboselevel))
943
944 #define VLOG_EVERY_N(verboselevel, n) \
945   LOG_IF_EVERY_N(INFO, VLOG_IS_ON(verboselevel), n)
946
947 #define VLOG_IF_EVERY_N(verboselevel, condition, n) \
948   LOG_IF_EVERY_N(INFO, (condition) && VLOG_IS_ON(verboselevel), n)
949
950 //
951 // This class more or less represents a particular log message.  You
952 // create an instance of LogMessage and then stream stuff to it.
953 // When you finish streaming to it, ~LogMessage is called and the
954 // full message gets streamed to the appropriate destination.
955 //
956 // You shouldn't actually use LogMessage's constructor to log things,
957 // though.  You should use the LOG() macro (and variants thereof)
958 // above.
959 class GOOGLE_GLOG_DLL_DECL LogMessage {
960 public:
961   enum {
962     // Passing kNoLogPrefix for the line number disables the
963     // log-message prefix. Useful for using the LogMessage
964     // infrastructure as a printing utility. See also the --log_prefix
965     // flag for controlling the log-message prefix on an
966     // application-wide basis.
967     kNoLogPrefix = -1
968   };
969
970   // LogStream inherit from non-DLL-exported class (std::ostrstream)
971   // and VC++ produces a warning for this situation.
972   // However, MSDN says "C4275 can be ignored in Microsoft Visual C++
973   // 2005 if you are deriving from a type in the Standard C++ Library"
974   // http://msdn.microsoft.com/en-us/library/3tdb471s(VS.80).aspx
975   // Let's just ignore the warning.
976 #ifdef _MSC_VER
977 # pragma warning(disable: 4275)
978 #endif
979   class GOOGLE_GLOG_DLL_DECL LogStream : public std::ostrstream {
980 #ifdef _MSC_VER
981 # pragma warning(default: 4275)
982 #endif
983   public:
984     LogStream(char *buf, int len, int ctr)
985       : ostrstream(buf, len),
986         ctr_(ctr) {
987       self_ = this;
988     }
989
990     int ctr() const { return ctr_; }
991     void set_ctr(int ctr) { ctr_ = ctr; }
992     LogStream* self() const { return self_; }
993
994   private:
995     int ctr_;  // Counter hack (for the LOG_EVERY_X() macro)
996     LogStream *self_;  // Consistency check hack
997   };
998
999 public:
1000   // icc 8 requires this typedef to avoid an internal compiler error.
1001   typedef void (LogMessage::*SendMethod)();
1002
1003   LogMessage(const char* file, int line, LogSeverity severity, int ctr,
1004              SendMethod send_method);
1005
1006   // Two special constructors that generate reduced amounts of code at
1007   // LOG call sites for common cases.
1008
1009   // Used for LOG(INFO): Implied are:
1010   // severity = INFO, ctr = 0, send_method = &LogMessage::SendToLog.
1011   //
1012   // Using this constructor instead of the more complex constructor above
1013   // saves 19 bytes per call site.
1014   LogMessage(const char* file, int line);
1015
1016   // Used for LOG(severity) where severity != INFO.  Implied
1017   // are: ctr = 0, send_method = &LogMessage::SendToLog
1018   //
1019   // Using this constructor instead of the more complex constructor above
1020   // saves 17 bytes per call site.
1021   LogMessage(const char* file, int line, LogSeverity severity);
1022
1023   // Constructor to log this message to a specified sink (if not NULL).
1024   // Implied are: ctr = 0, send_method = &LogMessage::SendToSinkAndLog if
1025   // also_send_to_log is true, send_method = &LogMessage::SendToSink otherwise.
1026   LogMessage(const char* file, int line, LogSeverity severity, LogSink* sink,
1027              bool also_send_to_log);
1028
1029   // Constructor where we also give a vector<string> pointer
1030   // for storing the messages (if the pointer is not NULL).
1031   // Implied are: ctr = 0, send_method = &LogMessage::SaveOrSendToLog.
1032   LogMessage(const char* file, int line, LogSeverity severity,
1033              std::vector<std::string>* outvec);
1034
1035   // Constructor where we also give a string pointer for storing the
1036   // message (if the pointer is not NULL).  Implied are: ctr = 0,
1037   // send_method = &LogMessage::WriteToStringAndLog.
1038   LogMessage(const char* file, int line, LogSeverity severity,
1039              std::string* message);
1040
1041   // A special constructor used for check failures
1042   LogMessage(const char* file, int line, const CheckOpString& result);
1043
1044   ~LogMessage();
1045
1046   // Flush a buffered message to the sink set in the constructor.  Always
1047   // called by the destructor, it may also be called from elsewhere if
1048   // needed.  Only the first call is actioned; any later ones are ignored.
1049   void Flush();
1050
1051   // An arbitrary limit on the length of a single log message.  This
1052   // is so that streaming can be done more efficiently.
1053   static const size_t kMaxLogMessageLen;
1054
1055   // Theses should not be called directly outside of logging.*,
1056   // only passed as SendMethod arguments to other LogMessage methods:
1057   void SendToLog();  // Actually dispatch to the logs
1058   void SendToSyslogAndLog();  // Actually dispatch to syslog and the logs
1059
1060   // Call abort() or similar to perform LOG(FATAL) crash.
1061   static void Fail() @ac_cv___attribute___noreturn@;
1062
1063   std::ostream& stream() { return *(data_->stream_); }
1064
1065   int preserved_errno() const { return data_->preserved_errno_; }
1066
1067   // Must be called without the log_mutex held.  (L < log_mutex)
1068   static int64 num_messages(int severity);
1069
1070 private:
1071   // Fully internal SendMethod cases:
1072   void SendToSinkAndLog();  // Send to sink if provided and dispatch to the logs
1073   void SendToSink();  // Send to sink if provided, do nothing otherwise.
1074
1075   // Write to string if provided and dispatch to the logs.
1076   void WriteToStringAndLog();
1077
1078   void SaveOrSendToLog();  // Save to stringvec if provided, else to logs
1079
1080   void Init(const char* file, int line, LogSeverity severity,
1081             void (LogMessage::*send_method)());
1082
1083   // Counts of messages sent at each priority:
1084   static int64 num_messages_[NUM_SEVERITIES];  // under log_mutex
1085
1086   // We keep the data in a separate struct so that each instance of
1087   // LogMessage uses less stack space.
1088   struct GOOGLE_GLOG_DLL_DECL LogMessageData {
1089     LogMessageData() {};
1090
1091     int preserved_errno_;      // preserved errno
1092     char* buf_;
1093     char* message_text_;  // Complete message text (points to selected buffer)
1094     LogStream* stream_alloc_;
1095     LogStream* stream_;
1096     char severity_;      // What level is this LogMessage logged at?
1097     int line_;                 // line number where logging call is.
1098     void (LogMessage::*send_method_)();  // Call this in destructor to send
1099     union {  // At most one of these is used: union to keep the size low.
1100       LogSink* sink_;             // NULL or sink to send message to
1101       std::vector<std::string>* outvec_; // NULL or vector to push message onto
1102       std::string* message_;             // NULL or string to write message into
1103     };
1104     time_t timestamp_;            // Time of creation of LogMessage
1105     struct ::tm tm_time_;         // Time of creation of LogMessage
1106     size_t num_prefix_chars_;     // # of chars of prefix in this message
1107     size_t num_chars_to_log_;     // # of chars of msg to send to log
1108     size_t num_chars_to_syslog_;  // # of chars of msg to send to syslog
1109     const char* basename_;        // basename of file that called LOG
1110     const char* fullname_;        // fullname of file that called LOG
1111     bool has_been_flushed_;       // false => data has not been flushed
1112     bool first_fatal_;            // true => this was first fatal msg
1113
1114     ~LogMessageData();
1115    private:
1116     LogMessageData(const LogMessageData&);
1117     void operator=(const LogMessageData&);
1118   };
1119
1120   static LogMessageData fatal_msg_data_exclusive_;
1121   static LogMessageData fatal_msg_data_shared_;
1122
1123   LogMessageData* allocated_;
1124   LogMessageData* data_;
1125
1126   friend class LogDestination;
1127
1128   LogMessage(const LogMessage&);
1129   void operator=(const LogMessage&);
1130 };
1131
1132 // This class happens to be thread-hostile because all instances share
1133 // a single data buffer, but since it can only be created just before
1134 // the process dies, we don't worry so much.
1135 class GOOGLE_GLOG_DLL_DECL LogMessageFatal : public LogMessage {
1136  public:
1137   LogMessageFatal(const char* file, int line);
1138   LogMessageFatal(const char* file, int line, const CheckOpString& result);
1139   ~LogMessageFatal() @ac_cv___attribute___noreturn@;
1140 };
1141
1142 // A non-macro interface to the log facility; (useful
1143 // when the logging level is not a compile-time constant).
1144 inline void LogAtLevel(int const severity, std::string const &msg) {
1145   LogMessage(__FILE__, __LINE__, severity).stream() << msg;
1146 }
1147
1148 // A macro alternative of LogAtLevel. New code may want to use this
1149 // version since there are two advantages: 1. this version outputs the
1150 // file name and the line number where this macro is put like other
1151 // LOG macros, 2. this macro can be used as C++ stream.
1152 #define LOG_AT_LEVEL(severity) LogMessage(__FILE__, __LINE__, severity).stream()
1153
1154 // A small helper for CHECK_NOTNULL().
1155 template <typename T>
1156 T* CheckNotNull(const char *file, int line, const char *names, T* t) {
1157   if (t == NULL) {
1158     LogMessageFatal(file, line, new std::string(names));
1159   }
1160   return t;
1161 }
1162
1163 // Allow folks to put a counter in the LOG_EVERY_X()'ed messages. This
1164 // only works if ostream is a LogStream. If the ostream is not a
1165 // LogStream you'll get an assert saying as much at runtime.
1166 GOOGLE_GLOG_DLL_DECL std::ostream& operator<<(std::ostream &os,
1167                                               const PRIVATE_Counter&);
1168
1169
1170 // Derived class for PLOG*() above.
1171 class GOOGLE_GLOG_DLL_DECL ErrnoLogMessage : public LogMessage {
1172  public:
1173
1174   ErrnoLogMessage(const char* file, int line, LogSeverity severity, int ctr,
1175                   void (LogMessage::*send_method)());
1176
1177   // Postpends ": strerror(errno) [errno]".
1178   ~ErrnoLogMessage();
1179
1180  private:
1181   ErrnoLogMessage(const ErrnoLogMessage&);
1182   void operator=(const ErrnoLogMessage&);
1183 };
1184
1185
1186 // This class is used to explicitly ignore values in the conditional
1187 // logging macros.  This avoids compiler warnings like "value computed
1188 // is not used" and "statement has no effect".
1189
1190 class GOOGLE_GLOG_DLL_DECL LogMessageVoidify {
1191  public:
1192   LogMessageVoidify() { }
1193   // This has to be an operator with a precedence lower than << but
1194   // higher than ?:
1195   void operator&(std::ostream&) { }
1196 };
1197
1198
1199 // Flushes all log files that contains messages that are at least of
1200 // the specified severity level.  Thread-safe.
1201 GOOGLE_GLOG_DLL_DECL void FlushLogFiles(LogSeverity min_severity);
1202
1203 // Flushes all log files that contains messages that are at least of
1204 // the specified severity level. Thread-hostile because it ignores
1205 // locking -- used for catastrophic failures.
1206 GOOGLE_GLOG_DLL_DECL void FlushLogFilesUnsafe(LogSeverity min_severity);
1207
1208 //
1209 // Set the destination to which a particular severity level of log
1210 // messages is sent.  If base_filename is "", it means "don't log this
1211 // severity".  Thread-safe.
1212 //
1213 GOOGLE_GLOG_DLL_DECL void SetLogDestination(LogSeverity severity,
1214                                             const char* base_filename);
1215
1216 //
1217 // Set the basename of the symlink to the latest log file at a given
1218 // severity.  If symlink_basename is empty, do not make a symlink.  If
1219 // you don't call this function, the symlink basename is the
1220 // invocation name of the program.  Thread-safe.
1221 //
1222 GOOGLE_GLOG_DLL_DECL void SetLogSymlink(LogSeverity severity,
1223                                         const char* symlink_basename);
1224
1225 //
1226 // Used to send logs to some other kind of destination
1227 // Users should subclass LogSink and override send to do whatever they want.
1228 // Implementations must be thread-safe because a shared instance will
1229 // be called from whichever thread ran the LOG(XXX) line.
1230 class GOOGLE_GLOG_DLL_DECL LogSink {
1231  public:
1232   virtual ~LogSink();
1233
1234   // Sink's logging logic (message_len is such as to exclude '\n' at the end).
1235   // This method can't use LOG() or CHECK() as logging system mutex(s) are held
1236   // during this call.
1237   virtual void send(LogSeverity severity, const char* full_filename,
1238                     const char* base_filename, int line,
1239                     const struct ::tm* tm_time,
1240                     const char* message, size_t message_len) = 0;
1241
1242   // Redefine this to implement waiting for
1243   // the sink's logging logic to complete.
1244   // It will be called after each send() returns,
1245   // but before that LogMessage exits or crashes.
1246   // By default this function does nothing.
1247   // Using this function one can implement complex logic for send()
1248   // that itself involves logging; and do all this w/o causing deadlocks and
1249   // inconsistent rearrangement of log messages.
1250   // E.g. if a LogSink has thread-specific actions, the send() method
1251   // can simply add the message to a queue and wake up another thread that
1252   // handles real logging while itself making some LOG() calls;
1253   // WaitTillSent() can be implemented to wait for that logic to complete.
1254   // See our unittest for an example.
1255   virtual void WaitTillSent();
1256
1257   // Returns the normal text output of the log message.
1258   // Can be useful to implement send().
1259   static std::string ToString(LogSeverity severity, const char* file, int line,
1260                               const struct ::tm* tm_time,
1261                               const char* message, size_t message_len);
1262 };
1263
1264 // Add or remove a LogSink as a consumer of logging data.  Thread-safe.
1265 GOOGLE_GLOG_DLL_DECL void AddLogSink(LogSink *destination);
1266 GOOGLE_GLOG_DLL_DECL void RemoveLogSink(LogSink *destination);
1267
1268 //
1269 // Specify an "extension" added to the filename specified via
1270 // SetLogDestination.  This applies to all severity levels.  It's
1271 // often used to append the port we're listening on to the logfile
1272 // name.  Thread-safe.
1273 //
1274 GOOGLE_GLOG_DLL_DECL void SetLogFilenameExtension(
1275     const char* filename_extension);
1276
1277 //
1278 // Make it so that all log messages of at least a particular severity
1279 // are logged to stderr (in addition to logging to the usual log
1280 // file(s)).  Thread-safe.
1281 //
1282 GOOGLE_GLOG_DLL_DECL void SetStderrLogging(LogSeverity min_severity);
1283
1284 //
1285 // Make it so that all log messages go only to stderr.  Thread-safe.
1286 //
1287 GOOGLE_GLOG_DLL_DECL void LogToStderr();
1288
1289 //
1290 // Make it so that all log messages of at least a particular severity are
1291 // logged via email to a list of addresses (in addition to logging to the
1292 // usual log file(s)).  The list of addresses is just a string containing
1293 // the email addresses to send to (separated by spaces, say).  Thread-safe.
1294 //
1295 GOOGLE_GLOG_DLL_DECL void SetEmailLogging(LogSeverity min_severity,
1296                                           const char* addresses);
1297
1298 // A simple function that sends email. dest is a commma-separated
1299 // list of addressess.  Thread-safe.
1300 GOOGLE_GLOG_DLL_DECL bool SendEmail(const char *dest,
1301                                     const char *subject, const char *body);
1302
1303 GOOGLE_GLOG_DLL_DECL const std::vector<std::string>& GetLoggingDirectories();
1304
1305 // For tests only:  Clear the internal [cached] list of logging directories to
1306 // force a refresh the next time GetLoggingDirectories is called.
1307 // Thread-hostile.
1308 void TestOnly_ClearLoggingDirectoriesList();
1309
1310 // Returns a set of existing temporary directories, which will be a
1311 // subset of the directories returned by GetLogginDirectories().
1312 // Thread-safe.
1313 GOOGLE_GLOG_DLL_DECL void GetExistingTempDirectories(
1314     std::vector<std::string>* list);
1315
1316 // Print any fatal message again -- useful to call from signal handler
1317 // so that the last thing in the output is the fatal message.
1318 // Thread-hostile, but a race is unlikely.
1319 GOOGLE_GLOG_DLL_DECL void ReprintFatalMessage();
1320
1321 // Truncate a log file that may be the append-only output of multiple
1322 // processes and hence can't simply be renamed/reopened (typically a
1323 // stdout/stderr).  If the file "path" is > "limit" bytes, copy the
1324 // last "keep" bytes to offset 0 and truncate the rest. Since we could
1325 // be racing with other writers, this approach has the potential to
1326 // lose very small amounts of data. For security, only follow symlinks
1327 // if the path is /proc/self/fd/*
1328 GOOGLE_GLOG_DLL_DECL void TruncateLogFile(const char *path,
1329                                           int64 limit, int64 keep);
1330
1331 // Truncate stdout and stderr if they are over the value specified by
1332 // --max_log_size; keep the final 1MB.  This function has the same
1333 // race condition as TruncateLogFile.
1334 GOOGLE_GLOG_DLL_DECL void TruncateStdoutStderr();
1335
1336 // Return the string representation of the provided LogSeverity level.
1337 // Thread-safe.
1338 GOOGLE_GLOG_DLL_DECL const char* GetLogSeverityName(LogSeverity severity);
1339
1340 // ---------------------------------------------------------------------
1341 // Implementation details that are not useful to most clients
1342 // ---------------------------------------------------------------------
1343
1344 // A Logger is the interface used by logging modules to emit entries
1345 // to a log.  A typical implementation will dump formatted data to a
1346 // sequence of files.  We also provide interfaces that will forward
1347 // the data to another thread so that the invoker never blocks.
1348 // Implementations should be thread-safe since the logging system
1349 // will write to them from multiple threads.
1350
1351 namespace base {
1352
1353 class GOOGLE_GLOG_DLL_DECL Logger {
1354  public:
1355   virtual ~Logger();
1356
1357   // Writes "message[0,message_len-1]" corresponding to an event that
1358   // occurred at "timestamp".  If "force_flush" is true, the log file
1359   // is flushed immediately.
1360   //
1361   // The input message has already been formatted as deemed
1362   // appropriate by the higher level logging facility.  For example,
1363   // textual log messages already contain timestamps, and the
1364   // file:linenumber header.
1365   virtual void Write(bool force_flush,
1366                      time_t timestamp,
1367                      const char* message,
1368                      int message_len) = 0;
1369
1370   // Flush any buffered messages
1371   virtual void Flush() = 0;
1372
1373   // Get the current LOG file size.
1374   // The returned value is approximate since some
1375   // logged data may not have been flushed to disk yet.
1376   virtual uint32 LogSize() = 0;
1377 };
1378
1379 // Get the logger for the specified severity level.  The logger
1380 // remains the property of the logging module and should not be
1381 // deleted by the caller.  Thread-safe.
1382 extern GOOGLE_GLOG_DLL_DECL Logger* GetLogger(LogSeverity level);
1383
1384 // Set the logger for the specified severity level.  The logger
1385 // becomes the property of the logging module and should not
1386 // be deleted by the caller.  Thread-safe.
1387 extern GOOGLE_GLOG_DLL_DECL void SetLogger(LogSeverity level, Logger* logger);
1388
1389 }
1390
1391 // glibc has traditionally implemented two incompatible versions of
1392 // strerror_r(). There is a poorly defined convention for picking the
1393 // version that we want, but it is not clear whether it even works with
1394 // all versions of glibc.
1395 // So, instead, we provide this wrapper that automatically detects the
1396 // version that is in use, and then implements POSIX semantics.
1397 // N.B. In addition to what POSIX says, we also guarantee that "buf" will
1398 // be set to an empty string, if this function failed. This means, in most
1399 // cases, you do not need to check the error code and you can directly
1400 // use the value of "buf". It will never have an undefined value.
1401 GOOGLE_GLOG_DLL_DECL int posix_strerror_r(int err, char *buf, size_t len);
1402
1403
1404 // A class for which we define operator<<, which does nothing.
1405 class GOOGLE_GLOG_DLL_DECL NullStream : public LogMessage::LogStream {
1406  public:
1407   // Initialize the LogStream so the messages can be written somewhere
1408   // (they'll never be actually displayed). This will be needed if a
1409   // NullStream& is implicitly converted to LogStream&, in which case
1410   // the overloaded NullStream::operator<< will not be invoked.
1411   NullStream() : LogMessage::LogStream(message_buffer_, 1, 0) { }
1412   NullStream(const char* /*file*/, int /*line*/,
1413              const CheckOpString& /*result*/) :
1414       LogMessage::LogStream(message_buffer_, 1, 0) { }
1415   NullStream &stream() { return *this; }
1416  private:
1417   // A very short buffer for messages (which we discard anyway). This
1418   // will be needed if NullStream& converted to LogStream& (e.g. as a
1419   // result of a conditional expression).
1420   char message_buffer_[2];
1421 };
1422
1423 // Do nothing. This operator is inline, allowing the message to be
1424 // compiled away. The message will not be compiled away if we do
1425 // something like (flag ? LOG(INFO) : LOG(ERROR)) << message; when
1426 // SKIP_LOG=WARNING. In those cases, NullStream will be implicitly
1427 // converted to LogStream and the message will be computed and then
1428 // quietly discarded.
1429 template<class T>
1430 inline NullStream& operator<<(NullStream &str, const T &value) { return str; }
1431
1432 // Similar to NullStream, but aborts the program (without stack
1433 // trace), like LogMessageFatal.
1434 class GOOGLE_GLOG_DLL_DECL NullStreamFatal : public NullStream {
1435  public:
1436   NullStreamFatal() { }
1437   NullStreamFatal(const char* file, int line, const CheckOpString& result) :
1438       NullStream(file, line, result) { }
1439   @ac_cv___attribute___noreturn@ ~NullStreamFatal() { _exit(1); }
1440 };
1441
1442 // Install a signal handler that will dump signal information and a stack
1443 // trace when the program crashes on certain signals.  We'll install the
1444 // signal handler for the following signals.
1445 //
1446 // SIGSEGV, SIGILL, SIGFPE, SIGABRT, SIGBUS, and SIGTERM.
1447 //
1448 // By default, the signal handler will write the failure dump to the
1449 // standard error.  You can customize the destination by installing your
1450 // own writer function by InstallFailureWriter() below.
1451 //
1452 // Note on threading:
1453 //
1454 // The function should be called before threads are created, if you want
1455 // to use the failure signal handler for all threads.  The stack trace
1456 // will be shown only for the thread that receives the signal.  In other
1457 // words, stack traces of other threads won't be shown.
1458 GOOGLE_GLOG_DLL_DECL void InstallFailureSignalHandler();
1459
1460 // Installs a function that is used for writing the failure dump.  "data"
1461 // is the pointer to the beginning of a message to be written, and "size"
1462 // is the size of the message.  You should not expect the data is
1463 // terminated with '\0'.
1464 GOOGLE_GLOG_DLL_DECL void InstallFailureWriter(
1465     void (*writer)(const char* data, int size));
1466
1467 @ac_google_end_namespace@
1468
1469 #endif // _LOGGING_H_