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