OR-Tools  9.3
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 = nullptr; \
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, nullptr); \
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 pointer 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. This is useful for capturing
456// messages and storing them somewhere more specific than the global log of the
457// process.
458// Argument types:
459// string* message;
460// LogSeverity severity;
461// The cast is to disambiguate null pointer 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 pointer 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 {
506 return GOOGLE_PREDICT_BRANCH_NOT_TAKEN(str_ != nullptr);
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 std::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 nullptr; \
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.
637 ==) // Compilation error with CHECK_EQ(nullptr, x)?
638DEFINE_CHECK_OP_IMPL(Check_NE, !=) // Use CHECK(x == nullptr) instead.
639DEFINE_CHECK_OP_IMPL(Check_LE, <=)
640DEFINE_CHECK_OP_IMPL(Check_LT, <)
641DEFINE_CHECK_OP_IMPL(Check_GE, >=)
642DEFINE_CHECK_OP_IMPL(Check_GT, >)
643#undef DEFINE_CHECK_OP_IMPL
644
645// Helper macro for binary operators.
646// Don't use this macro directly in your code, use CHECK_EQ et al below.
647
648#if defined(STATIC_ANALYSIS)
649// Only for static analysis tool to know that it is equivalent to assert
650#define CHECK_OP_LOG(name, op, val1, val2, log) CHECK((val1)op(val2))
651#elif DCHECK_IS_ON()
652// In debug mode, avoid constructing CheckOpStrings if possible,
653// to reduce the overhead of CHECK statments by 2x.
654// Real DCHECK-heavy tests have seen 1.5x speedups.
655
656// The meaning of "string" might be different between now and
657// when this macro gets invoked (e.g., if someone is experimenting
658// with other string implementations that get defined after this
659// file is included). Save the current meaning now and use it
660// in the macro.
661typedef std::string _Check_string;
662#define CHECK_OP_LOG(name, op, val1, val2, log) \
663 while (google::_Check_string* _result = google::Check##name##Impl( \
664 google::GetReferenceableValue(val1), \
665 google::GetReferenceableValue(val2), #val1 " " #op " " #val2)) \
666 log(__FILE__, __LINE__, google::CheckOpString(_result)).stream()
667#else
668// In optimized mode, use CheckOpString to hint to compiler that
669// the while condition is unlikely.
670#define CHECK_OP_LOG(name, op, val1, val2, log) \
671 while (google::CheckOpString _result = google::Check##name##Impl( \
672 google::GetReferenceableValue(val1), \
673 google::GetReferenceableValue(val2), #val1 " " #op " " #val2)) \
674 log(__FILE__, __LINE__, _result).stream()
675#endif // STATIC_ANALYSIS, DCHECK_IS_ON()
676
677#if GOOGLE_STRIP_LOG <= 3
678#define CHECK_OP(name, op, val1, val2) \
679 CHECK_OP_LOG(name, op, val1, val2, google::LogMessageFatal)
680#else
681#define CHECK_OP(name, op, val1, val2) \
682 CHECK_OP_LOG(name, op, val1, val2, google::NullStreamFatal)
683#endif // STRIP_LOG <= 3
684
685// Equality/Inequality checks - compare two values, and log a FATAL message
686// including the two values when the result is not as expected. The values
687// must have operator<<(ostream, ...) defined.
688//
689// You may append to the error message like so:
690// CHECK_NE(1, 2) << ": The world must be ending!";
691//
692// We are very careful to ensure that each argument is evaluated exactly
693// once, and that anything which is legal to pass as a function argument is
694// legal here. In particular, the arguments may be temporary expressions
695// which will end up being destroyed at the end of the apparent statement,
696// for example:
697// CHECK_EQ(string("abc")[1], 'b');
698//
699// WARNING: These don't compile correctly if one of the arguments is a pointer
700// and the other is NULL. To work around this, simply static_cast NULL to the
701// type of the desired pointer.
702
703#define CHECK_EQ(val1, val2) CHECK_OP(_EQ, ==, val1, val2)
704#define CHECK_NE(val1, val2) CHECK_OP(_NE, !=, val1, val2)
705#define CHECK_LE(val1, val2) CHECK_OP(_LE, <=, val1, val2)
706#define CHECK_LT(val1, val2) CHECK_OP(_LT, <, val1, val2)
707#define CHECK_GE(val1, val2) CHECK_OP(_GE, >=, val1, val2)
708#define CHECK_GT(val1, val2) CHECK_OP(_GT, >, val1, val2)
709
710// Check that the input is non-null. This very useful in constructor initializer
711// lists.
712
713#define CHECK_NOTNULL(val) \
714 google::CheckNotNull(__FILE__, __LINE__, "'" #val "' Must be non null", (val))
715
716// Helper functions for string comparisons.
717// To avoid bloat, the definitions are in logging.cc.
718#define DECLARE_CHECK_STROP_IMPL(func, expected) \
719 GOOGLE_GLOG_DLL_DECL std::string* Check##func##expected##Impl( \
720 const char* s1, const char* s2, const char* names);
721DECLARE_CHECK_STROP_IMPL(strcmp, true)
722DECLARE_CHECK_STROP_IMPL(strcmp, false)
723DECLARE_CHECK_STROP_IMPL(strcasecmp, true)
724DECLARE_CHECK_STROP_IMPL(strcasecmp, false)
725#undef DECLARE_CHECK_STROP_IMPL
726
727// Helper macro for string comparisons.
728// Don't use this macro directly in your code, use CHECK_STREQ et al below.
729#define CHECK_STROP(func, op, expected, s1, s2) \
730 while (google::CheckOpString _result = google::Check##func##expected##Impl( \
731 (s1), (s2), #s1 " " #op " " #s2)) \
732 LOG(FATAL) << *_result.str_
733
734// String (char*) equality/inequality checks.
735// CASE versions are case-insensitive.
736//
737// Note that "s1" and "s2" may be temporary strings which are destroyed
738// by the compiler at the end of the current "full expression"
739// (e.g. CHECK_STREQ(Foo().c_str(), Bar().c_str())).
740
741#define CHECK_STREQ(s1, s2) CHECK_STROP(strcmp, ==, true, s1, s2)
742#define CHECK_STRNE(s1, s2) CHECK_STROP(strcmp, !=, false, s1, s2)
743#define CHECK_STRCASEEQ(s1, s2) CHECK_STROP(strcasecmp, ==, true, s1, s2)
744#define CHECK_STRCASENE(s1, s2) CHECK_STROP(strcasecmp, !=, false, s1, s2)
745
746#define CHECK_INDEX(I, A) CHECK(I < (sizeof(A) / sizeof(A[0])))
747#define CHECK_BOUND(B, A) CHECK(B <= (sizeof(A) / sizeof(A[0])))
748
749#define CHECK_DOUBLE_EQ(val1, val2) \
750 do { \
751 CHECK_LE((val1), (val2) + 0.000000000000001L); \
752 CHECK_GE((val1), (val2)-0.000000000000001L); \
753 } while (0)
754
755#define CHECK_NEAR(val1, val2, margin) \
756 do { \
757 CHECK_LE((val1), (val2) + (margin)); \
758 CHECK_GE((val1), (val2) - (margin)); \
759 } while (0)
760
761// perror()..googly style!
762//
763// PLOG() and PLOG_IF() and PCHECK() behave exactly like their LOG* and
764// CHECK equivalents with the addition that they postpend a description
765// of the current state of errno to their output lines.
766
767#define PLOG(severity) GOOGLE_PLOG(severity, 0).stream()
768
769#define GOOGLE_PLOG(severity, counter) \
770 google::ErrnoLogMessage(__FILE__, __LINE__, google::GLOG_##severity, \
771 counter, &google::LogMessage::SendToLog)
772
773#define PLOG_IF(severity, condition) \
774 static_cast<void>(0), \
775 !(condition) ? (void)0 : google::LogMessageVoidify() & PLOG(severity)
776
777// A CHECK() macro that postpends errno if the condition is false. E.g.
778//
779// if (poll(fds, nfds, timeout) == -1) { PCHECK(errno == EINTR); ... }
780#define PCHECK(condition) \
781 PLOG_IF(FATAL, GOOGLE_PREDICT_BRANCH_NOT_TAKEN(!(condition))) \
782 << "Check failed: " #condition " "
783
784// A CHECK() macro that lets you assert the success of a function that
785// returns -1 and sets errno in case of an error. E.g.
786//
787// CHECK_ERR(mkdir(path, 0700));
788//
789// or
790//
791// int fd = open(filename, flags); CHECK_ERR(fd) << ": open " << filename;
792#define CHECK_ERR(invocation) \
793 PLOG_IF(FATAL, GOOGLE_PREDICT_BRANCH_NOT_TAKEN((invocation) == -1)) \
794 << #invocation
795
796// Use macro expansion to create, for each use of LOG_EVERY_N(), static
797// variables with the __LINE__ expansion as part of the variable name.
798#define LOG_EVERY_N_VARNAME(base, line) LOG_EVERY_N_VARNAME_CONCAT(base, line)
799#define LOG_EVERY_N_VARNAME_CONCAT(base, line) base##line
800
801#define LOG_OCCURRENCES LOG_EVERY_N_VARNAME(occurrences_, __LINE__)
802#define LOG_OCCURRENCES_MOD_N LOG_EVERY_N_VARNAME(occurrences_mod_n_, __LINE__)
803
804#define SOME_KIND_OF_LOG_EVERY_N(severity, n, what_to_do) \
805 static int LOG_OCCURRENCES = 0, LOG_OCCURRENCES_MOD_N = 0; \
806 ++LOG_OCCURRENCES; \
807 if (++LOG_OCCURRENCES_MOD_N > n) LOG_OCCURRENCES_MOD_N -= n; \
808 if (LOG_OCCURRENCES_MOD_N == 1) \
809 google::LogMessage(__FILE__, __LINE__, google::GLOG_##severity, \
810 LOG_OCCURRENCES, &what_to_do) \
811 .stream()
812
813#define SOME_KIND_OF_LOG_IF_EVERY_N(severity, condition, n, what_to_do) \
814 static int LOG_OCCURRENCES = 0, LOG_OCCURRENCES_MOD_N = 0; \
815 ++LOG_OCCURRENCES; \
816 if (condition && \
817 ((LOG_OCCURRENCES_MOD_N = (LOG_OCCURRENCES_MOD_N + 1) % n) == (1 % n))) \
818 google::LogMessage(__FILE__, __LINE__, google::GLOG_##severity, \
819 LOG_OCCURRENCES, &what_to_do) \
820 .stream()
821
822#define SOME_KIND_OF_PLOG_EVERY_N(severity, n, what_to_do) \
823 static int LOG_OCCURRENCES = 0, LOG_OCCURRENCES_MOD_N = 0; \
824 ++LOG_OCCURRENCES; \
825 if (++LOG_OCCURRENCES_MOD_N > n) LOG_OCCURRENCES_MOD_N -= n; \
826 if (LOG_OCCURRENCES_MOD_N == 1) \
827 google::ErrnoLogMessage(__FILE__, __LINE__, google::GLOG_##severity, \
828 LOG_OCCURRENCES, &what_to_do) \
829 .stream()
830
831#define SOME_KIND_OF_LOG_FIRST_N(severity, n, what_to_do) \
832 static int LOG_OCCURRENCES = 0; \
833 if (LOG_OCCURRENCES <= n) ++LOG_OCCURRENCES; \
834 if (LOG_OCCURRENCES <= n) \
835 google::LogMessage(__FILE__, __LINE__, google::GLOG_##severity, \
836 LOG_OCCURRENCES, &what_to_do) \
837 .stream()
838
839namespace logging_internal {
840template <bool>
842struct CrashReason;
843} // namespace logging_internal
844
845#define LOG_EVERY_N(severity, n) \
846 SOME_KIND_OF_LOG_EVERY_N(severity, (n), google::LogMessage::SendToLog)
847
848#define SYSLOG_EVERY_N(severity, n) \
849 SOME_KIND_OF_LOG_EVERY_N(severity, (n), \
850 google::LogMessage::SendToSyslogAndLog)
851
852#define PLOG_EVERY_N(severity, n) \
853 SOME_KIND_OF_PLOG_EVERY_N(severity, (n), google::LogMessage::SendToLog)
854
855#define LOG_FIRST_N(severity, n) \
856 SOME_KIND_OF_LOG_FIRST_N(severity, (n), google::LogMessage::SendToLog)
857
858#define LOG_IF_EVERY_N(severity, condition, n) \
859 SOME_KIND_OF_LOG_IF_EVERY_N(severity, (condition), (n), \
860 google::LogMessage::SendToLog)
861
862// We want the special COUNTER value available for LOG_EVERY_X()'ed messages
864
865#ifdef _MSC_VER
866// wingdi.h defines ERROR to be 0. When we call LOG(ERROR), it gets
867// substituted with 0, and it expands to COMPACT_GOOGLE_LOG_0. To allow us
868// to keep using this syntax, we define this macro to do the same thing
869// as COMPACT_GOOGLE_LOG_ERROR.
870#define COMPACT_GOOGLE_LOG_0 COMPACT_GOOGLE_LOG_ERROR
871#define SYSLOG_0 SYSLOG_ERROR
872#define LOG_TO_STRING_0 LOG_TO_STRING_ERROR
873// Needed for LOG_IS_ON(ERROR).
874const LogSeverity GLOG_0 = GLOG_ERROR;
875#endif
876
877// Plus some debug-logging macros that get compiled to nothing for production
878
879#if DCHECK_IS_ON()
880
881#define DLOG(severity) LOG(severity)
882#define DVLOG(verboselevel) VLOG(verboselevel)
883#define DLOG_IF(severity, condition) LOG_IF(severity, condition)
884#define DLOG_EVERY_N(severity, n) LOG_EVERY_N(severity, n)
885#define DLOG_IF_EVERY_N(severity, condition, n) \
886 LOG_IF_EVERY_N(severity, condition, n)
887#define DLOG_ASSERT(condition) LOG_ASSERT(condition)
888
889// debug-only checking. executed if DCHECK_IS_ON().
890#define DCHECK(condition) CHECK(condition)
891#define DCHECK_EQ(val1, val2) CHECK_EQ(val1, val2)
892#define DCHECK_NE(val1, val2) CHECK_NE(val1, val2)
893#define DCHECK_LE(val1, val2) CHECK_LE(val1, val2)
894#define DCHECK_LT(val1, val2) CHECK_LT(val1, val2)
895#define DCHECK_GE(val1, val2) CHECK_GE(val1, val2)
896#define DCHECK_GT(val1, val2) CHECK_GT(val1, val2)
897#define DCHECK_NOTNULL(val) CHECK_NOTNULL(val)
898#define DCHECK_STREQ(str1, str2) CHECK_STREQ(str1, str2)
899#define DCHECK_STRCASEEQ(str1, str2) CHECK_STRCASEEQ(str1, str2)
900#define DCHECK_STRNE(str1, str2) CHECK_STRNE(str1, str2)
901#define DCHECK_STRCASENE(str1, str2) CHECK_STRCASENE(str1, str2)
902
903#else // !DCHECK_IS_ON()
904
905#define DLOG(severity) \
906 static_cast<void>(0), \
907 true ? (void)0 : google::LogMessageVoidify() & LOG(severity)
908
909#define DVLOG(verboselevel) \
910 static_cast<void>(0), (true || !VLOG_IS_ON(verboselevel)) \
911 ? (void)0 \
912 : google::LogMessageVoidify() & LOG(INFO)
913
914#define DLOG_IF(severity, condition) \
915 static_cast<void>(0), (true || !(condition)) \
916 ? (void)0 \
917 : google::LogMessageVoidify() & LOG(severity)
918
919#define DLOG_EVERY_N(severity, n) \
920 static_cast<void>(0), \
921 true ? (void)0 : google::LogMessageVoidify() & LOG(severity)
922
923#define DLOG_IF_EVERY_N(severity, condition, n) \
924 static_cast<void>(0), (true || !(condition)) \
925 ? (void)0 \
926 : google::LogMessageVoidify() & LOG(severity)
927
928#define DLOG_ASSERT(condition) \
929 static_cast<void>(0), true ? (void)0 : LOG_ASSERT(condition)
930
931// MSVC warning C4127: conditional expression is constant
932#define DCHECK(condition) \
933 GLOG_MSVC_PUSH_DISABLE_WARNING(4127) \
934 while (false) GLOG_MSVC_POP_WARNING() CHECK(condition)
935
936#define DCHECK_EQ(val1, val2) \
937 GLOG_MSVC_PUSH_DISABLE_WARNING(4127) \
938 while (false) GLOG_MSVC_POP_WARNING() CHECK_EQ(val1, val2)
939
940#define DCHECK_NE(val1, val2) \
941 GLOG_MSVC_PUSH_DISABLE_WARNING(4127) \
942 while (false) GLOG_MSVC_POP_WARNING() CHECK_NE(val1, val2)
943
944#define DCHECK_LE(val1, val2) \
945 GLOG_MSVC_PUSH_DISABLE_WARNING(4127) \
946 while (false) GLOG_MSVC_POP_WARNING() CHECK_LE(val1, val2)
947
948#define DCHECK_LT(val1, val2) \
949 GLOG_MSVC_PUSH_DISABLE_WARNING(4127) \
950 while (false) GLOG_MSVC_POP_WARNING() CHECK_LT(val1, val2)
951
952#define DCHECK_GE(val1, val2) \
953 GLOG_MSVC_PUSH_DISABLE_WARNING(4127) \
954 while (false) GLOG_MSVC_POP_WARNING() CHECK_GE(val1, val2)
955
956#define DCHECK_GT(val1, val2) \
957 GLOG_MSVC_PUSH_DISABLE_WARNING(4127) \
958 while (false) GLOG_MSVC_POP_WARNING() CHECK_GT(val1, val2)
959
960// You may see warnings in release mode if you don't use the return
961// value of DCHECK_NOTNULL. Please just use DCHECK for such cases.
962#define DCHECK_NOTNULL(val) (val)
963
964#define DCHECK_STREQ(str1, str2) \
965 GLOG_MSVC_PUSH_DISABLE_WARNING(4127) \
966 while (false) GLOG_MSVC_POP_WARNING() CHECK_STREQ(str1, str2)
967
968#define DCHECK_STRCASEEQ(str1, str2) \
969 GLOG_MSVC_PUSH_DISABLE_WARNING(4127) \
970 while (false) GLOG_MSVC_POP_WARNING() CHECK_STRCASEEQ(str1, str2)
971
972#define DCHECK_STRNE(str1, str2) \
973 GLOG_MSVC_PUSH_DISABLE_WARNING(4127) \
974 while (false) GLOG_MSVC_POP_WARNING() CHECK_STRNE(str1, str2)
975
976#define DCHECK_STRCASENE(str1, str2) \
977 GLOG_MSVC_PUSH_DISABLE_WARNING(4127) \
978 while (false) GLOG_MSVC_POP_WARNING() CHECK_STRCASENE(str1, str2)
979
980#endif // DCHECK_IS_ON()
981
982// Log only in verbose mode.
983
984#define VLOG(verboselevel) LOG_IF(INFO, VLOG_IS_ON(verboselevel))
985
986#define VLOG_EVERY_N(verboselevel, n) \
987 LOG_IF_EVERY_N(INFO, VLOG_IS_ON(verboselevel), n)
988
989namespace base_logging {
990
991// LogMessage::LogStream is a std::ostream backed by this streambuf.
992// This class ignores overflow and leaves two bytes at the end of the
993// buffer to allow for a '\n' and '\0'.
994class GOOGLE_GLOG_DLL_DECL LogStreamBuf : public std::streambuf {
995 public:
996 // REQUIREMENTS: "len" must be >= 2 to account for the '\n' and '\0'.
997 LogStreamBuf(char* buf, int len) { setp(buf, buf + len - 2); }
998
999 // This effectively ignores overflow.
1000 virtual int_type overflow(int_type ch) { return ch; }
1001
1002 // Legacy public ostrstream method.
1003 size_t pcount() const { return pptr() - pbase(); }
1004 char* pbase() const { return std::streambuf::pbase(); }
1005};
1006
1007} // namespace base_logging
1008
1009//
1010// This class more or less represents a particular log message. You
1011// create an instance of LogMessage and then stream stuff to it.
1012// When you finish streaming to it, ~LogMessage is called and the
1013// full message gets streamed to the appropriate destination.
1014//
1015// You shouldn't actually use LogMessage's constructor to log things,
1016// though. You should use the LOG() macro (and variants thereof)
1017// above.
1019 public:
1020 enum {
1021 // Passing kNoLogPrefix for the line number disables the
1022 // log-message prefix. Useful for using the LogMessage
1023 // infrastructure as a printing utility. See also the --log_prefix
1024 // flag for controlling the log-message prefix on an
1025 // application-wide basis.
1026 kNoLogPrefix = -1
1028
1029 // LogStream inherit from non-DLL-exported class (std::ostrstream)
1030 // and VC++ produces a warning for this situation.
1031 // However, MSDN says "C4275 can be ignored in Microsoft Visual C++
1032 // 2005 if you are deriving from a type in the Standard C++ Library"
1033 // http://msdn.microsoft.com/en-us/library/3tdb471s(VS.80).aspx
1034 // Let's just ignore the warning.
1036 class GOOGLE_GLOG_DLL_DECL LogStream : public std::ostream {
1038 public:
1039 LogStream(char* buf, int len, int ctr)
1040 : std::ostream(nullptr), streambuf_(buf, len), ctr_(ctr), self_(this) {
1041 rdbuf(&streambuf_);
1042 }
1043
1044 int ctr() const { return ctr_; }
1045 void set_ctr(int ctr) { ctr_ = ctr; }
1046 LogStream* self() const { return self_; }
1047
1048 // Legacy std::streambuf methods.
1049 size_t pcount() const { return streambuf_.pcount(); }
1050 char* pbase() const { return streambuf_.pbase(); }
1051 char* str() const { return pbase(); }
1052
1053 private:
1054 LogStream(const LogStream&);
1055 LogStream& operator=(const LogStream&);
1056 base_logging::LogStreamBuf streambuf_;
1057 int ctr_; // Counter hack (for the LOG_EVERY_X() macro)
1058 LogStream* self_; // Consistency check hack
1059 };
1060
1061 public:
1062 // icc 8 requires this typedef to avoid an internal compiler error.
1063 typedef void (LogMessage::*SendMethod)();
1064
1065 LogMessage(const char* file, int line, LogSeverity severity, int ctr,
1066 SendMethod send_method);
1067
1068 // Two special constructors that generate reduced amounts of code at
1069 // LOG call sites for common cases.
1070
1071 // Used for LOG(INFO): Implied are:
1072 // severity = INFO, ctr = 0, send_method = &LogMessage::SendToLog.
1073 //
1074 // Using this constructor instead of the more complex constructor above
1075 // saves 19 bytes per call site.
1076 LogMessage(const char* file, int line);
1077
1078 // Used for LOG(severity) where severity != INFO. Implied
1079 // are: ctr = 0, send_method = &LogMessage::SendToLog
1080 //
1081 // Using this constructor instead of the more complex constructor above
1082 // saves 17 bytes per call site.
1083 LogMessage(const char* file, int line, LogSeverity severity);
1084
1085 // Constructor to log this message to a specified sink (if not null).
1086 // Implied are: ctr = 0, send_method = &LogMessage::SendToSinkAndLog if
1087 // also_send_to_log is true, send_method = &LogMessage::SendToSink otherwise.
1088 LogMessage(const char* file, int line, LogSeverity severity, LogSink* sink,
1089 bool also_send_to_log);
1090
1091 // Constructor where we also give a vector<string> pointer
1092 // for storing the messages (if the pointer is not null).
1093 // Implied are: ctr = 0, send_method = &LogMessage::SaveOrSendToLog.
1094 LogMessage(const char* file, int line, LogSeverity severity,
1095 std::vector<std::string>* outvec);
1096
1097 // Constructor where we also give a string pointer for storing the
1098 // message (if the pointer is not null). Implied are: ctr = 0,
1099 // send_method = &LogMessage::WriteToStringAndLog.
1100 LogMessage(const char* file, int line, LogSeverity severity,
1101 std::string* message);
1102
1103 // A special constructor used for check failures
1104 LogMessage(const char* file, int line, const CheckOpString& result);
1105
1106 ~LogMessage();
1107
1108 // Flush a buffered message to the sink set in the constructor. Always
1109 // called by the destructor, it may also be called from elsewhere if
1110 // needed. Only the first call is actioned; any later ones are ignored.
1111 void Flush();
1112
1113 // An arbitrary limit on the length of a single log message. This
1114 // is so that streaming can be done more efficiently.
1115 static const size_t kMaxLogMessageLen;
1116
1117 // Theses should not be called directly outside of logging.*,
1118 // only passed as SendMethod arguments to other LogMessage methods:
1119 void SendToLog(); // Actually dispatch to the logs
1120 void SendToSyslogAndLog(); // Actually dispatch to syslog and the logs
1121
1122 // Call abort() or similar to perform LOG(FATAL) crash.
1123 static void ATTRIBUTE_NORETURN Fail();
1124
1125 std::ostream& stream();
1126
1127 int preserved_errno() const;
1128
1129 // Must be called without the log_mutex held. (L < log_mutex)
1130 static int64_t num_messages(int severity);
1131
1132 struct LogMessageData;
1133
1134 private:
1135 // Fully internal SendMethod cases:
1136 void SendToSinkAndLog(); // Send to sink if provided and dispatch to the logs
1137 void SendToSink(); // Send to sink if provided, do nothing otherwise.
1138
1139 // Write to string if provided and dispatch to the logs.
1140 void WriteToStringAndLog();
1141
1142 void SaveOrSendToLog(); // Save to stringvec if provided, else to logs
1143
1144 void Init(const char* file, int line, LogSeverity severity,
1145 void (LogMessage::*send_method)());
1146
1147 // Used to fill in crash information during LOG(FATAL) failures.
1148 void RecordCrashReason(logging_internal::CrashReason* reason);
1149
1150 // Counts of messages sent at each priority:
1151 static int64_t num_messages_[NUM_SEVERITIES]; // under log_mutex
1152
1153 // We keep the data in a separate struct so that each instance of
1154 // LogMessage uses less stack space.
1155 LogMessageData* allocated_;
1156 LogMessageData* data_;
1157
1158 friend class LogDestination;
1159
1160 LogMessage(const LogMessage&);
1161 void operator=(const LogMessage&);
1162};
1163
1164// This class happens to be thread-hostile because all instances share
1165// a single data buffer, but since it can only be created just before
1166// the process dies, we don't worry so much.
1168 public:
1169 LogMessageFatal(const char* file, int line);
1170 LogMessageFatal(const char* file, int line, const CheckOpString& result);
1172};
1173
1174// A non-macro interface to the log facility; (useful
1175// when the logging level is not a compile-time constant).
1176inline void LogAtLevel(int const severity, std::string const& msg) {
1177 LogMessage(__FILE__, __LINE__, severity).stream() << msg;
1178}
1179
1180// A macro alternative of LogAtLevel. New code may want to use this
1181// version since there are two advantages: 1. this version outputs the
1182// file name and the line number where this macro is put like other
1183// LOG macros, 2. this macro can be used as C++ stream.
1184#define LOG_AT_LEVEL(severity) \
1185 google::LogMessage(__FILE__, __LINE__, severity).stream()
1186
1187// Check if it's compiled in C++11 mode.
1188//
1189// GXX_EXPERIMENTAL_CXX0X is defined by gcc and clang up to at least
1190// gcc-4.7 and clang-3.1 (2011-12-13). __cplusplus was defined to 1
1191// in gcc before 4.7 (Crosstool 16) and clang before 3.1, but is
1192// defined according to the language version in effect thereafter.
1193// Microsoft Visual Studio 14 (2015) sets __cplusplus==199711 despite
1194// reasonably good C++11 support, so we set LANG_CXX for it and
1195// newer versions (_MSC_VER >= 1900).
1196#if (defined(__GXX_EXPERIMENTAL_CXX0X__) || __cplusplus >= 201103L || \
1197 (defined(_MSC_VER) && _MSC_VER >= 1900))
1198// Helper for CHECK_NOTNULL().
1199//
1200// In C++11, all cases can be handled by a single function. Since the value
1201// category of the argument is preserved (also for rvalue references),
1202// member initializer lists like the one below will compile correctly:
1203//
1204// Foo()
1205// : x_(CHECK_NOTNULL(MethodReturningUniquePtr())) {}
1206template <typename T>
1207T CheckNotNull(const char* file, int line, const char* names, T&& t) {
1208 if (t == nullptr) {
1209 LogMessageFatal(file, line, new std::string(names));
1210 }
1211 return std::forward<T>(t);
1212}
1213
1214#else
1215
1216// A small helper for CHECK_NOTNULL().
1217template <typename T>
1218T* CheckNotNull(const char* file, int line, const char* names, T* t) {
1219 if (t == nullptr) {
1220 LogMessageFatal(file, line, new std::string(names));
1221 }
1222 return t;
1223}
1224#endif
1225
1226// Allow folks to put a counter in the LOG_EVERY_X()'ed messages. This
1227// only works if ostream is a LogStream. If the ostream is not a
1228// LogStream you'll get an assert saying as much at runtime.
1229GOOGLE_GLOG_DLL_DECL std::ostream& operator<<(std::ostream& os,
1230 const PRIVATE_Counter&);
1231
1232// Derived class for PLOG*() above.
1234 public:
1235 ErrnoLogMessage(const char* file, int line, LogSeverity severity, int ctr,
1236 void (LogMessage::*send_method)());
1237
1238 // Postpends ": strerror(errno) [errno]".
1240
1241 private:
1243 void operator=(const ErrnoLogMessage&);
1244};
1245
1246// This class is used to explicitly ignore values in the conditional
1247// logging macros. This avoids compiler warnings like "value computed
1248// is not used" and "statement has no effect".
1249
1251 public:
1253 // This has to be an operator with a precedence lower than << but
1254 // higher than ?:
1255 void operator&(std::ostream&) {}
1256};
1257
1258// Flushes all log files that contains messages that are at least of
1259// the specified severity level. Thread-safe.
1261
1262// Flushes all log files that contains messages that are at least of
1263// the specified severity level. Thread-hostile because it ignores
1264// locking -- used for catastrophic failures.
1266
1267//
1268// Set the destination to which a particular severity level of log
1269// messages is sent. If base_filename is "", it means "don't log this
1270// severity". Thread-safe.
1271//
1273 const char* base_filename);
1274
1275//
1276// Set the basename of the symlink to the latest log file at a given
1277// severity. If symlink_basename is empty, do not make a symlink. If
1278// you don't call this function, the symlink basename is the
1279// invocation name of the program. Thread-safe.
1280//
1282 const char* symlink_basename);
1283
1284//
1285// Used to send logs to some other kind of destination
1286// Users should subclass LogSink and override send to do whatever they want.
1287// Implementations must be thread-safe because a shared instance will
1288// be called from whichever thread ran the LOG(XXX) line.
1290 public:
1291 virtual ~LogSink();
1292
1293 // Sink's logging logic (message_len is such as to exclude '\n' at the end).
1294 // This method can't use LOG() or CHECK() as logging system mutex(s) are held
1295 // during this call.
1296 virtual void send(LogSeverity severity, const char* full_filename,
1297 const char* base_filename, int line,
1298 const struct ::tm* tm_time, const char* message,
1299 size_t message_len) = 0;
1300
1301 // Redefine this to implement waiting for
1302 // the sink's logging logic to complete.
1303 // It will be called after each send() returns,
1304 // but before that LogMessage exits or crashes.
1305 // By default this function does nothing.
1306 // Using this function one can implement complex logic for send()
1307 // that itself involves logging; and do all this w/o causing deadlocks and
1308 // inconsistent rearrangement of log messages.
1309 // E.g. if a LogSink has thread-specific actions, the send() method
1310 // can simply add the message to a queue and wake up another thread that
1311 // handles real logging while itself making some LOG() calls;
1312 // WaitTillSent() can be implemented to wait for that logic to complete.
1313 // See our unittest for an example.
1314 virtual void WaitTillSent();
1315
1316 // Returns the normal text output of the log message.
1317 // Can be useful to implement send().
1318 static std::string ToString(LogSeverity severity, const char* file, int line,
1319 const struct ::tm* tm_time, const char* message,
1320 size_t message_len);
1321};
1322
1323// Add or remove a LogSink as a consumer of logging data. Thread-safe.
1324GOOGLE_GLOG_DLL_DECL void AddLogSink(LogSink* destination);
1325GOOGLE_GLOG_DLL_DECL void RemoveLogSink(LogSink* destination);
1326
1327//
1328// Specify an "extension" added to the filename specified via
1329// SetLogDestination. This applies to all severity levels. It's
1330// often used to append the port we're listening on to the logfile
1331// name. Thread-safe.
1332//
1334 const char* filename_extension);
1335
1336//
1337// Make it so that all log messages of at least a particular severity
1338// are logged to stderr (in addition to logging to the usual log
1339// file(s)). Thread-safe.
1340//
1342
1343//
1344// Make it so that all log messages go only to stderr. Thread-safe.
1345//
1347
1348GOOGLE_GLOG_DLL_DECL const std::vector<std::string>& GetLoggingDirectories();
1349
1350// For tests only: Clear the internal [cached] list of logging directories to
1351// force a refresh the next time GetLoggingDirectories is called.
1352// Thread-hostile.
1354
1355// Returns a set of existing temporary directories, which will be a
1356// subset of the directories returned by GetLogginDirectories().
1357// Thread-safe.
1359 std::vector<std::string>* list);
1360
1361// Print any fatal message again -- useful to call from signal handler
1362// so that the last thing in the output is the fatal message.
1363// Thread-hostile, but a race is unlikely.
1365
1366// Return the string representation of the provided LogSeverity level.
1367// Thread-safe.
1369
1370// ---------------------------------------------------------------------
1371// Implementation details that are not useful to most clients
1372// ---------------------------------------------------------------------
1373
1374// A Logger is the interface used by logging modules to emit entries
1375// to a log. A typical implementation will dump formatted data to a
1376// sequence of files. We also provide interfaces that will forward
1377// the data to another thread so that the invoker never blocks.
1378// Implementations should be thread-safe since the logging system
1379// will write to them from multiple threads.
1380
1381namespace base {
1382
1384 public:
1385 virtual ~Logger();
1386
1387 // Writes "message[0,message_len-1]" corresponding to an event that
1388 // occurred at "timestamp". If "force_flush" is true, the log file
1389 // is flushed immediately.
1390 //
1391 // The input message has already been formatted as deemed
1392 // appropriate by the higher level logging facility. For example,
1393 // textual log messages already contain timestamps, and the
1394 // file:linenumber header.
1395 virtual void Write(bool force_flush, time_t timestamp, const char* message,
1396 int message_len) = 0;
1397
1398 // Flush any buffered messages
1399 virtual void Flush() = 0;
1400
1401 // Get the current LOG file size.
1402 // The returned value is approximate since some
1403 // logged data may not have been flushed to disk yet.
1404 virtual uint32_t LogSize() = 0;
1405};
1406
1407// Get the logger for the specified severity level. The logger
1408// remains the property of the logging module and should not be
1409// deleted by the caller. Thread-safe.
1411
1412// Set the logger for the specified severity level. The logger
1413// becomes the property of the logging module and should not
1414// be deleted by the caller. Thread-safe.
1415extern GOOGLE_GLOG_DLL_DECL void SetLogger(LogSeverity level, Logger* logger);
1416
1417} // namespace base
1418
1419// glibc has traditionally implemented two incompatible versions of
1420// strerror_r(). There is a poorly defined convention for picking the
1421// version that we want, but it is not clear whether it even works with
1422// all versions of glibc.
1423// So, instead, we provide this wrapper that automatically detects the
1424// version that is in use, and then implements POSIX semantics.
1425// N.B. In addition to what POSIX says, we also guarantee that "buf" will
1426// be set to an empty string, if this function failed. This means, in most
1427// cases, you do not need to check the error code and you can directly
1428// use the value of "buf". It will never have an undefined value.
1429// DEPRECATED: Use StrError(int) instead.
1430GOOGLE_GLOG_DLL_DECL int posix_strerror_r(int err, char* buf, size_t len);
1431
1432// A thread-safe replacement for strerror(). Returns a string describing the
1433// given POSIX error code.
1434GOOGLE_GLOG_DLL_DECL std::string StrError(int err);
1435
1436// A class for which we define operator<<, which does nothing.
1438 public:
1439 // Initialize the LogStream so the messages can be written somewhere
1440 // (they'll never be actually displayed). This will be needed if a
1441 // NullStream& is implicitly converted to LogStream&, in which case
1442 // the overloaded NullStream::operator<< will not be invoked.
1443 NullStream() : LogMessage::LogStream(message_buffer_, 1, 0) {}
1444 NullStream(const char* /*file*/, int /*line*/,
1445 const CheckOpString& /*result*/)
1446 : LogMessage::LogStream(message_buffer_, 1, 0) {}
1447 NullStream& stream() { return *this; }
1448
1449 private:
1450 // A very short buffer for messages (which we discard anyway). This
1451 // will be needed if NullStream& converted to LogStream& (e.g. as a
1452 // result of a conditional expression).
1453 char message_buffer_[2];
1454};
1455
1456// Do nothing. This operator is inline, allowing the message to be
1457// compiled away. The message will not be compiled away if we do
1458// something like (flag ? LOG(INFO) : LOG(ERROR)) << message; when
1459// SKIP_LOG=WARNING. In those cases, NullStream will be implicitly
1460// converted to LogStream and the message will be computed and then
1461// quietly discarded.
1462template <class T>
1463inline NullStream& operator<<(NullStream& str, const T&) {
1464 return str;
1465}
1466
1467// Similar to NullStream, but aborts the program (without stack
1468// trace), like LogMessageFatal.
1470 public:
1472 NullStreamFatal(const char* file, int line, const CheckOpString& result)
1473 : NullStream(file, line, result) {}
1474 ATTRIBUTE_NORETURN ~NullStreamFatal() throw() { _exit(1); }
1475};
1476} // namespace google
1477
1478#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:718
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)
LogStreamBuf(char *buf, int len)
Definition: base/logging.h:997
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