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