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