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