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