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