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