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