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