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