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