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