OR-Tools  8.2
base/logging.h
Go to the documentation of this file.
1// Copyright 2010-2018 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 <iosfwd>
23#include <ostream>
24#include <sstream>
25#include <string>
26#if defined(__GNUC__) && defined(__linux__)
27#include <unistd.h>
28#endif
29#include <vector>
30
35#include "ortools/base/macros.h"
37
38#define QCHECK CHECK
39#define ABSL_DIE_IF_NULL CHECK_NOTNULL
40#define CHECK_OK(x) CHECK((x).ok())
41
42// used by or-tools non C++ ports to bridge with the C++ layer.
44
45#if defined(_MSC_VER)
46#define GLOG_MSVC_PUSH_DISABLE_WARNING(n) \
47 __pragma(warning(push)) __pragma(warning(disable : n))
48#define GLOG_MSVC_POP_WARNING() __pragma(warning(pop))
49#define ATTRIBUTE_NOINLINE
50#define ATTRIBUTE_NORETURN __declspec(noreturn)
51#else
52#define GLOG_MSVC_PUSH_DISABLE_WARNING(n)
53#define GLOG_MSVC_POP_WARNING()
54#define ATTRIBUTE_NOINLINE __attribute__((noinline))
55#define ATTRIBUTE_NORETURN __attribute__((noreturn))
56#endif
57
58// The global value of GOOGLE_STRIP_LOG. All the messages logged to
59// LOG(XXX) with severity less than GOOGLE_STRIP_LOG will not be displayed.
60// If it can be determined at compile time that the message will not be
61// printed, the statement will be compiled out.
62//
63// Example: to strip out all INFO and WARNING messages, use the value
64// of 2 below. To make an exception for WARNING messages from a single
65// file, add "#define GOOGLE_STRIP_LOG 1" to that file _before_ including
66// base/logging.h
67#ifndef GOOGLE_STRIP_LOG
68#define GOOGLE_STRIP_LOG 0
69#endif
70
71// GCC can be told that a certain branch is not likely to be taken (for
72// instance, a CHECK failure), and use that information in static analysis.
73// Giving it this information can help it optimize for the common case in
74// the absence of better information (ie. -fprofile-arcs).
75//
76#ifndef GOOGLE_PREDICT_BRANCH_NOT_TAKEN
77#if !defined(_MSC_VER)
78#define GOOGLE_PREDICT_BRANCH_NOT_TAKEN(x) (__builtin_expect(x, 0))
79#else
80#define GOOGLE_PREDICT_BRANCH_NOT_TAKEN(x) x
81#endif
82#endif
83
84#ifndef GOOGLE_PREDICT_FALSE
85#if !defined(_MSC_VER)
86#define GOOGLE_PREDICT_FALSE(x) (__builtin_expect(x, 0))
87#else
88#define GOOGLE_PREDICT_FALSE(x) x
89#endif
90#endif
91
92#ifndef GOOGLE_PREDICT_TRUE
93#if !defined(_MSC_VER)
94#define GOOGLE_PREDICT_TRUE(x) (__builtin_expect(!!(x), 1))
95#else
96#define GOOGLE_PREDICT_TRUE(x) x
97#endif
98#endif
99
100// Make a bunch of macros for logging. The way to log things is to stream
101// things to LOG(<a particular severity level>). E.g.,
102//
103// LOG(INFO) << "Found " << num_cookies << " cookies";
104//
105// You can capture log messages in a string, rather than reporting them
106// immediately:
107//
108// vector<string> errors;
109// LOG_STRING(ERROR, &errors) << "Couldn't parse cookie #" << cookie_num;
110//
111// This pushes back the new error onto 'errors'; if given a NULL pointer,
112// it reports the error via LOG(ERROR).
113//
114// You can also do conditional logging:
115//
116// LOG_IF(INFO, num_cookies > 10) << "Got lots of cookies";
117//
118// You can also do occasional logging (log every n'th occurrence of an
119// event):
120//
121// LOG_EVERY_N(INFO, 10) << "Got the " << google::COUNTER << "th cookie";
122//
123// The above will cause log messages to be output on the 1st, 11th, 21st, ...
124// times it is executed. Note that the special google::COUNTER value is used
125// to identify which repetition is happening.
126//
127// You can also do occasional conditional logging (log every n'th
128// occurrence of an event, when condition is satisfied):
129//
130// LOG_IF_EVERY_N(INFO, (size > 1024), 10) << "Got the " << google::COUNTER
131// << "th big cookie";
132//
133// You can log messages the first N times your code executes a line. E.g.
134//
135// LOG_FIRST_N(INFO, 20) << "Got the " << google::COUNTER << "th cookie";
136//
137// Outputs log messages for the first 20 times it is executed.
138//
139// Analogous SYSLOG, SYSLOG_IF, and SYSLOG_EVERY_N macros are available.
140// These log to syslog as well as to the normal logs. If you use these at
141// all, you need to be aware that syslog can drastically reduce performance,
142// especially if it is configured for remote logging! Don't use these
143// unless you fully understand this and have a concrete need to use them.
144// Even then, try to minimize your use of them.
145//
146// There are also "debug mode" logging macros like the ones above:
147//
148// DLOG(INFO) << "Found cookies";
149//
150// DLOG_IF(INFO, num_cookies > 10) << "Got lots of cookies";
151//
152// DLOG_EVERY_N(INFO, 10) << "Got the " << google::COUNTER << "th cookie";
153//
154// All "debug mode" logging is compiled away to nothing for non-debug mode
155// compiles.
156//
157// We also have
158//
159// LOG_ASSERT(assertion);
160// DLOG_ASSERT(assertion);
161//
162// which is syntactic sugar for {,D}LOG_IF(FATAL, assert fails) << assertion;
163//
164// There are "verbose level" logging macros. They look like
165//
166// VLOG(1) << "I'm printed when you run the program with --v=1 or more";
167// VLOG(2) << "I'm printed when you run the program with --v=2 or more";
168//
169// These always log at the INFO log level (when they log at all).
170// The verbose logging can also be turned on module-by-module. For instance,
171// --vmodule=mapreduce=2,file=1,gfs*=3 --v=0
172// will cause:
173// a. VLOG(2) and lower messages to be printed from mapreduce.{h,cc}
174// b. VLOG(1) and lower messages to be printed from file.{h,cc}
175// c. VLOG(3) and lower messages to be printed from files prefixed with "gfs"
176// d. VLOG(0) and lower messages to be printed from elsewhere
177//
178// The wildcarding functionality shown by (c) supports both '*' (match
179// 0 or more characters) and '?' (match any single character) wildcards.
180//
181// There's also VLOG_IS_ON(n) "verbose level" condition macro. To be used as
182//
183// if (VLOG_IS_ON(2)) {
184// // do some logging preparation and logging
185// // that can't be accomplished with just VLOG(2) << ...;
186// }
187//
188// There are also VLOG_IF, VLOG_EVERY_N and VLOG_IF_EVERY_N "verbose level"
189// condition macros for sample cases, when some extra computation and
190// preparation for logs is not needed.
191// VLOG_IF(1, (size > 1024))
192// << "I'm printed when size is more than 1024 and when you run the "
193// "program with --v=1 or more";
194// VLOG_EVERY_N(1, 10)
195// << "I'm printed every 10th occurrence, and when you run the program "
196// "with --v=1 or more. Present occurrence is " << google::COUNTER;
197// VLOG_IF_EVERY_N(1, (size > 1024), 10)
198// << "I'm printed on every 10th occurrence of case when size is more "
199// " than 1024, when you run the program with --v=1 or more. ";
200// "Present occurrence is " << google::COUNTER;
201//
202// The supported severity levels for macros that allow you to specify one
203// are (in increasing order of severity) INFO, WARNING, ERROR, and FATAL.
204// Note that messages of a given severity are logged not only in the
205// logfile for that severity, but also in all logfiles of lower severity.
206// E.g., a message of severity FATAL will be logged to the logfiles of
207// severity FATAL, ERROR, WARNING, and INFO.
208//
209// There is also the special severity of DFATAL, which logs FATAL in
210// debug mode, ERROR in normal mode.
211//
212// Very important: logging a message at the FATAL severity level causes
213// the program to terminate (after the message is logged).
214//
215// Unless otherwise specified, logs will be written to the filename
216// "<program name>.<hostname>.<user name>.log.<severity level>.", followed
217// by the date, time, and pid (you can't prevent the date, time, and pid
218// from being in the filename).
219//
220// The logging code takes two flags:
221// --v=# set the verbose level
222// --logtostderr log all the messages to stderr instead of to logfiles
223
224// LOG LINE PREFIX FORMAT
225//
226// Log lines have this form:
227//
228// Lmmdd hh:mm:ss.uuuuuu threadid file:line] msg...
229//
230// where the fields are defined as follows:
231//
232// L A single character, representing the log level
233// (eg 'I' for INFO)
234// mm The month (zero padded; ie May is '05')
235// dd The day (zero padded)
236// hh:mm:ss.uuuuuu Time in hours, minutes and fractional seconds
237// threadid The space-padded thread ID as returned by GetTID()
238// (this matches the PID on Linux)
239// file The file name
240// line The line number
241// msg The user-supplied message
242//
243// Example:
244//
245// I1103 11:57:31.739339 24395 google.cc:2341] Command line: ./some_prog
246// I1103 11:57:31.739403 24395 google.cc:2342] Process id 24395
247//
248// NOTE: although the microseconds are useful for comparing events on
249// a single machine, clocks on different machines may not be well
250// synchronized. Hence, use caution when comparing the low bits of
251// timestamps from different machines.
252
253// Set whether log messages go to stderr instead of logfiles
254ABSL_DECLARE_FLAG(bool, logtostderr);
255
256// Set whether log messages go to stderr in addition to logfiles.
257ABSL_DECLARE_FLAG(bool, alsologtostderr);
258
259// Set color messages logged to stderr (if supported by terminal).
260ABSL_DECLARE_FLAG(bool, colorlogtostderr);
261
262// Log messages at a level >= this flag are automatically sent to
263// stderr in addition to log files.
264ABSL_DECLARE_FLAG(int, stderrthreshold);
265
266// Set whether the log prefix should be prepended to each line of output.
267ABSL_DECLARE_FLAG(bool, log_prefix);
268
269// Log messages at a level <= this flag are buffered.
270// Log messages at a higher level are flushed immediately.
271ABSL_DECLARE_FLAG(int, logbuflevel);
272
273// Sets the maximum number of seconds which logs may be buffered for.
274ABSL_DECLARE_FLAG(int, logbufsecs);
275
276// Log suppression level: messages logged at a lower level than this
277// are suppressed.
278ABSL_DECLARE_FLAG(int, minloglevel);
279
280// If specified, logfiles are written into this directory instead of the
281// default logging directory.
282ABSL_DECLARE_FLAG(std::string, log_dir);
283
284// Set the log file mode.
285ABSL_DECLARE_FLAG(int, logfile_mode);
286
287// Sets the path of the directory into which to put additional links
288// to the log files.
289ABSL_DECLARE_FLAG(std::string, log_link);
290
291ABSL_DECLARE_FLAG(int, v); // in vlog_is_on.cc
292
293// Sets the maximum log file size (in MB).
294ABSL_DECLARE_FLAG(int, max_log_size);
295
296// Sets whether to avoid logging to the disk if the disk is full.
297ABSL_DECLARE_FLAG(bool, stop_logging_if_full_disk);
298
299// Log messages below the GOOGLE_STRIP_LOG level will be compiled away for
300// security reasons. See LOG(severtiy) below.
301
302// A few definitions of macros that don't generate much code. Since
303// LOG(INFO) and its ilk are used all over our code, it's
304// better to have compact code for these operations.
305
306#if GOOGLE_STRIP_LOG == 0
307#define COMPACT_GOOGLE_LOG_INFO google::LogMessage(__FILE__, __LINE__)
308#define LOG_TO_STRING_INFO(message) \
309 google::LogMessage(__FILE__, __LINE__, google::GLOG_INFO, message)
310#else
311#define COMPACT_GOOGLE_LOG_INFO google::NullStream()
312#define LOG_TO_STRING_INFO(message) google::NullStream()
313#endif
314
315#if GOOGLE_STRIP_LOG <= 1
316#define COMPACT_GOOGLE_LOG_WARNING \
317 google::LogMessage(__FILE__, __LINE__, google::GLOG_WARNING)
318#define LOG_TO_STRING_WARNING(message) \
319 google::LogMessage(__FILE__, __LINE__, google::GLOG_WARNING, message)
320#else
321#define COMPACT_GOOGLE_LOG_WARNING google::NullStream()
322#define LOG_TO_STRING_WARNING(message) google::NullStream()
323#endif
324
325#if GOOGLE_STRIP_LOG <= 2
326#define COMPACT_GOOGLE_LOG_ERROR \
327 google::LogMessage(__FILE__, __LINE__, google::GLOG_ERROR)
328#define LOG_TO_STRING_ERROR(message) \
329 google::LogMessage(__FILE__, __LINE__, google::GLOG_ERROR, message)
330#else
331#define COMPACT_GOOGLE_LOG_ERROR google::NullStream()
332#define LOG_TO_STRING_ERROR(message) google::NullStream()
333#endif
334
335#if GOOGLE_STRIP_LOG <= 3
336#define COMPACT_GOOGLE_LOG_FATAL google::LogMessageFatal(__FILE__, __LINE__)
337#define LOG_TO_STRING_FATAL(message) \
338 google::LogMessage(__FILE__, __LINE__, google::GLOG_FATAL, message)
339#else
340#define COMPACT_GOOGLE_LOG_FATAL google::NullStreamFatal()
341#define LOG_TO_STRING_FATAL(message) google::NullStreamFatal()
342#endif
343
344#if defined(NDEBUG) && !defined(DCHECK_ALWAYS_ON)
345#define DCHECK_IS_ON() 0
346#else
347#define DCHECK_IS_ON() 1
348#endif
349
350// For DFATAL, we want to use LogMessage (as opposed to
351// LogMessageFatal), to be consistent with the original behavior.
352#if !DCHECK_IS_ON()
353#define COMPACT_GOOGLE_LOG_DFATAL COMPACT_GOOGLE_LOG_ERROR
354#elif GOOGLE_STRIP_LOG <= 3
355#define COMPACT_GOOGLE_LOG_DFATAL \
356 google::LogMessage(__FILE__, __LINE__, google::GLOG_FATAL)
357#else
358#define COMPACT_GOOGLE_LOG_DFATAL google::NullStreamFatal()
359#endif
360
361#define GOOGLE_LOG_INFO(counter) \
362 google::LogMessage(__FILE__, __LINE__, google::GLOG_INFO, counter, \
363 &google::LogMessage::SendToLog)
364#define SYSLOG_INFO(counter) \
365 google::LogMessage(__FILE__, __LINE__, google::GLOG_INFO, counter, \
366 &google::LogMessage::SendToSyslogAndLog)
367#define GOOGLE_LOG_WARNING(counter) \
368 google::LogMessage(__FILE__, __LINE__, google::GLOG_WARNING, counter, \
369 &google::LogMessage::SendToLog)
370#define SYSLOG_WARNING(counter) \
371 google::LogMessage(__FILE__, __LINE__, google::GLOG_WARNING, counter, \
372 &google::LogMessage::SendToSyslogAndLog)
373#define GOOGLE_LOG_ERROR(counter) \
374 google::LogMessage(__FILE__, __LINE__, google::GLOG_ERROR, counter, \
375 &google::LogMessage::SendToLog)
376#define SYSLOG_ERROR(counter) \
377 google::LogMessage(__FILE__, __LINE__, google::GLOG_ERROR, counter, \
378 &google::LogMessage::SendToSyslogAndLog)
379#define GOOGLE_LOG_FATAL(counter) \
380 google::LogMessage(__FILE__, __LINE__, google::GLOG_FATAL, counter, \
381 &google::LogMessage::SendToLog)
382#define SYSLOG_FATAL(counter) \
383 google::LogMessage(__FILE__, __LINE__, google::GLOG_FATAL, counter, \
384 &google::LogMessage::SendToSyslogAndLog)
385#define GOOGLE_LOG_DFATAL(counter) \
386 google::LogMessage(__FILE__, __LINE__, google::DFATAL_LEVEL, counter, \
387 &google::LogMessage::SendToLog)
388#define SYSLOG_DFATAL(counter) \
389 google::LogMessage(__FILE__, __LINE__, google::DFATAL_LEVEL, counter, \
390 &google::LogMessage::SendToSyslogAndLog)
391
392#if defined(WIN32) || defined(_WIN32) || defined(__WIN32__) || \
393 defined(__CYGWIN__) || defined(__CYGWIN32__)
394// A very useful logging macro to log windows errors:
395#define LOG_SYSRESULT(result) \
396 if (FAILED(HRESULT_FROM_WIN32(result))) { \
397 LPSTR message = NULL; \
398 LPSTR msg = reinterpret_cast<LPSTR>(&message); \
399 DWORD message_length = FormatMessageA( \
400 FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM, 0, \
401 result, 0, msg, 100, NULL); \
402 if (message_length > 0) { \
403 google::LogMessage(__FILE__, __LINE__, google::GLOG_ERROR, 0, \
404 &google::LogMessage::SendToLog) \
405 .stream() \
406 << reinterpret_cast<const char*>(message); \
407 LocalFree(message); \
408 } \
409 }
410#endif
411
412// We use the preprocessor's merging operator, "##", so that, e.g.,
413// LOG(INFO) becomes the token GOOGLE_LOG_INFO. There's some funny
414// subtle difference between ostream member streaming functions (e.g.,
415// ostream::operator<<(int) and ostream non-member streaming functions
416// (e.g., ::operator<<(ostream&, string&): it turns out that it's
417// impossible to stream something like a string directly to an unnamed
418// ostream. We employ a neat hack by calling the stream() member
419// function of LogMessage which seems to avoid the problem.
420#define LOG(severity) COMPACT_GOOGLE_LOG_##severity.stream()
421#define SYSLOG(severity) SYSLOG_##severity(0).stream()
422
423namespace google {
424
425// Initialize google's logging library. You will see the program name
426// specified by argv0 in log outputs.
427GOOGLE_GLOG_DLL_DECL void InitGoogleLogging(const char* argv0);
428
429// Shutdown google's logging library.
431
432// Install a function which will be called after LOG(FATAL).
433GOOGLE_GLOG_DLL_DECL void InstallFailureFunction(void (*fail_func)());
434
435class LogSink; // defined below
436
437// If a non-NULL sink pointer is given, we push this message to that sink.
438// For LOG_TO_SINK we then do normal LOG(severity) logging as well.
439// This is useful for capturing messages and passing/storing them
440// somewhere more specific than the global log of the process.
441// Argument types:
442// LogSink* sink;
443// LogSeverity severity;
444// The cast is to disambiguate NULL arguments.
445#define LOG_TO_SINK(sink, severity) \
446 google::LogMessage(__FILE__, __LINE__, google::GLOG_##severity, \
447 static_cast<google::LogSink*>(sink), true) \
448 .stream()
449#define LOG_TO_SINK_BUT_NOT_TO_LOGFILE(sink, severity) \
450 google::LogMessage(__FILE__, __LINE__, google::GLOG_##severity, \
451 static_cast<google::LogSink*>(sink), false) \
452 .stream()
453
454// If a non-NULL string pointer is given, we write this message to that string.
455// We then do normal LOG(severity) logging as well.
456// This is useful for capturing messages and storing them somewhere more
457// specific than the global log of the process.
458// Argument types:
459// string* message;
460// LogSeverity severity;
461// The cast is to disambiguate NULL arguments.
462// NOTE: LOG(severity) expands to LogMessage().stream() for the specified
463// severity.
464#define LOG_TO_STRING(severity, message) \
465 LOG_TO_STRING_##severity(static_cast<string*>(message)).stream()
466
467// If a non-NULL pointer is given, we push the message onto the end
468// of a vector of strings; otherwise, we report it with LOG(severity).
469// This is handy for capturing messages and perhaps passing them back
470// to the caller, rather than reporting them immediately.
471// Argument types:
472// LogSeverity severity;
473// vector<string> *outvec;
474// The cast is to disambiguate NULL arguments.
475#define LOG_STRING(severity, outvec) \
476 LOG_TO_STRING_##severity(static_cast<std::vector<std::string>*>(outvec)) \
477 .stream()
478
479#define LOG_IF(severity, condition) \
480 static_cast<void>(0), \
481 !(condition) ? (void)0 : google::LogMessageVoidify() & LOG(severity)
482#define SYSLOG_IF(severity, condition) \
483 static_cast<void>(0), \
484 !(condition) ? (void)0 : google::LogMessageVoidify() & SYSLOG(severity)
485
486#define LOG_ASSERT(condition) \
487 LOG_IF(FATAL, !(condition)) << "Assert failed: " #condition
488#define SYSLOG_ASSERT(condition) \
489 SYSLOG_IF(FATAL, !(condition)) << "Assert failed: " #condition
490
491// CHECK dies with a fatal error if condition is not true. It is *not*
492// controlled by DCHECK_IS_ON(), so the check will be executed regardless of
493// compilation mode. Therefore, it is safe to do things like:
494// CHECK(fp->Write(x) == 4)
495#define CHECK(condition) \
496 LOG_IF(FATAL, GOOGLE_PREDICT_BRANCH_NOT_TAKEN(!(condition))) \
497 << "Check failed: " #condition " "
498
499// A container for a string pointer which can be evaluated to a bool -
500// true iff the pointer is NULL.
502 CheckOpString(std::string* str) : str_(str) {}
503 // No destructor: if str_ is non-NULL, we're about to LOG(FATAL),
504 // so there's no point in cleaning up str_.
505 operator bool() const {
507 }
508 std::string* str_;
509};
510
511// Function is overloaded for integral types to allow static const
512// integrals declared in classes and not defined to be used as arguments to
513// CHECK* macros. It's not encouraged though.
514template <class T>
515inline const T& GetReferenceableValue(const T& t) {
516 return t;
517}
518inline char GetReferenceableValue(char t) { return t; }
519inline unsigned char GetReferenceableValue(unsigned char t) { return t; }
520inline signed char GetReferenceableValue(signed char t) { return t; }
521inline int16 GetReferenceableValue(int16 t) { return t; }
522inline uint16 GetReferenceableValue(uint16 t) { return t; }
523inline int GetReferenceableValue(int t) { return t; }
524inline unsigned int GetReferenceableValue(unsigned int t) { return t; }
525inline int64 GetReferenceableValue(int64 t) { return t; }
526inline uint64 GetReferenceableValue(uint64 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
566namespace base {
567namespace internal {
568
569// If "s" is less than base_logging::INFO, returns base_logging::INFO.
570// If "s" is greater than base_logging::FATAL, returns
571// base_logging::ERROR. Otherwise, returns "s".
573
574} // namespace internal
575
576// A helper class for formatting "expr (V1 vs. V2)" in a CHECK_XX
577// statement. See MakeCheckOpString for sample usage. Other
578// approaches were considered: use of a template method (e.g.,
579// base::BuildCheckOpString(exprtext, base::Print<T1>, &v1,
580// base::Print<T2>, &v2), however this approach has complications
581// related to volatile arguments and function-pointer arguments).
583 public:
584 // Inserts "exprtext" and " (" to the stream.
585 explicit CheckOpMessageBuilder(const char* exprtext);
586 // Deletes "stream_".
588 // For inserting the first variable.
589 std::ostream* ForVar1() { return stream_; }
590 // For inserting the second variable (adds an intermediate " vs. ").
591 std::ostream* ForVar2();
592 // Get the result (inserts the closing ")").
593 std::string* NewString();
594
595 private:
596 std::ostringstream* stream_;
597};
598
599} // namespace base
600
601template <typename T1, typename T2>
602std::string* MakeCheckOpString(const T1& v1, const T2& v2,
603 const char* exprtext) {
604 base::CheckOpMessageBuilder comb(exprtext);
607 return comb.NewString();
608}
609
610// Helper functions for CHECK_OP macro.
611// The (int, int) specialization works around the issue that the compiler
612// will not instantiate the template version of the function on values of
613// unnamed enum type - see comment below.
614#define DEFINE_CHECK_OP_IMPL(name, op) \
615 template <typename T1, typename T2> \
616 inline std::string* name##Impl(const T1& v1, const T2& v2, \
617 const char* exprtext) { \
618 if (GOOGLE_PREDICT_TRUE(v1 op v2)) \
619 return NULL; \
620 else \
621 return MakeCheckOpString(v1, v2, exprtext); \
622 } \
623 inline std::string* name##Impl(int v1, int v2, const char* exprtext) { \
624 return name##Impl<int, int>(v1, v2, exprtext); \
625 }
626
627// We use the full name Check_EQ, Check_NE, etc. in case the file including
628// base/logging.h provides its own #defines for the simpler names EQ, NE, etc.
629// This happens if, for example, those are used as token names in a
630// yacc grammar.
631DEFINE_CHECK_OP_IMPL(Check_EQ, ==) // Compilation error with CHECK_EQ(NULL, x)?
632DEFINE_CHECK_OP_IMPL(Check_NE, !=) // Use CHECK(x == NULL) instead.
633DEFINE_CHECK_OP_IMPL(Check_LE, <=)
634DEFINE_CHECK_OP_IMPL(Check_LT, <)
635DEFINE_CHECK_OP_IMPL(Check_GE, >=)
636DEFINE_CHECK_OP_IMPL(Check_GT, >)
637#undef DEFINE_CHECK_OP_IMPL
638
639// Helper macro for binary operators.
640// Don't use this macro directly in your code, use CHECK_EQ et al below.
641
642#if defined(STATIC_ANALYSIS)
643// Only for static analysis tool to know that it is equivalent to assert
644#define CHECK_OP_LOG(name, op, val1, val2, log) CHECK((val1)op(val2))
645#elif DCHECK_IS_ON()
646// In debug mode, avoid constructing CheckOpStrings if possible,
647// to reduce the overhead of CHECK statments by 2x.
648// Real DCHECK-heavy tests have seen 1.5x speedups.
649
650// The meaning of "string" might be different between now and
651// when this macro gets invoked (e.g., if someone is experimenting
652// with other string implementations that get defined after this
653// file is included). Save the current meaning now and use it
654// in the macro.
655typedef std::string _Check_string;
656#define CHECK_OP_LOG(name, op, val1, val2, log) \
657 while (google::_Check_string* _result = google::Check##name##Impl( \
658 google::GetReferenceableValue(val1), \
659 google::GetReferenceableValue(val2), #val1 " " #op " " #val2)) \
660 log(__FILE__, __LINE__, google::CheckOpString(_result)).stream()
661#else
662// In optimized mode, use CheckOpString to hint to compiler that
663// the while condition is unlikely.
664#define CHECK_OP_LOG(name, op, val1, val2, log) \
665 while (google::CheckOpString _result = google::Check##name##Impl( \
666 google::GetReferenceableValue(val1), \
667 google::GetReferenceableValue(val2), #val1 " " #op " " #val2)) \
668 log(__FILE__, __LINE__, _result).stream()
669#endif // STATIC_ANALYSIS, DCHECK_IS_ON()
670
671#if GOOGLE_STRIP_LOG <= 3
672#define CHECK_OP(name, op, val1, val2) \
673 CHECK_OP_LOG(name, op, val1, val2, google::LogMessageFatal)
674#else
675#define CHECK_OP(name, op, val1, val2) \
676 CHECK_OP_LOG(name, op, val1, val2, google::NullStreamFatal)
677#endif // STRIP_LOG <= 3
678
679// Equality/Inequality checks - compare two values, and log a FATAL message
680// including the two values when the result is not as expected. The values
681// must have operator<<(ostream, ...) defined.
682//
683// You may append to the error message like so:
684// CHECK_NE(1, 2) << ": The world must be ending!";
685//
686// We are very careful to ensure that each argument is evaluated exactly
687// once, and that anything which is legal to pass as a function argument is
688// legal here. In particular, the arguments may be temporary expressions
689// which will end up being destroyed at the end of the apparent statement,
690// for example:
691// CHECK_EQ(string("abc")[1], 'b');
692//
693// WARNING: These don't compile correctly if one of the arguments is a pointer
694// and the other is NULL. To work around this, simply static_cast NULL to the
695// type of the desired pointer.
696
697#define CHECK_EQ(val1, val2) CHECK_OP(_EQ, ==, val1, val2)
698#define CHECK_NE(val1, val2) CHECK_OP(_NE, !=, val1, val2)
699#define CHECK_LE(val1, val2) CHECK_OP(_LE, <=, val1, val2)
700#define CHECK_LT(val1, val2) CHECK_OP(_LT, <, val1, val2)
701#define CHECK_GE(val1, val2) CHECK_OP(_GE, >=, val1, val2)
702#define CHECK_GT(val1, val2) CHECK_OP(_GT, >, val1, val2)
703
704// Check that the input is non NULL. This very useful in constructor
705// initializer lists.
706
707#define CHECK_NOTNULL(val) \
708 google::CheckNotNull(__FILE__, __LINE__, "'" #val "' Must be non NULL", (val))
709
710// Helper functions for string comparisons.
711// To avoid bloat, the definitions are in logging.cc.
712#define DECLARE_CHECK_STROP_IMPL(func, expected) \
713 GOOGLE_GLOG_DLL_DECL std::string* Check##func##expected##Impl( \
714 const char* s1, const char* s2, const char* names);
715DECLARE_CHECK_STROP_IMPL(strcmp, true)
716DECLARE_CHECK_STROP_IMPL(strcmp, false)
717DECLARE_CHECK_STROP_IMPL(strcasecmp, true)
718DECLARE_CHECK_STROP_IMPL(strcasecmp, false)
719#undef DECLARE_CHECK_STROP_IMPL
720
721// Helper macro for string comparisons.
722// Don't use this macro directly in your code, use CHECK_STREQ et al below.
723#define CHECK_STROP(func, op, expected, s1, s2) \
724 while (google::CheckOpString _result = google::Check##func##expected##Impl( \
725 (s1), (s2), #s1 " " #op " " #s2)) \
726 LOG(FATAL) << *_result.str_
727
728// String (char*) equality/inequality checks.
729// CASE versions are case-insensitive.
730//
731// Note that "s1" and "s2" may be temporary strings which are destroyed
732// by the compiler at the end of the current "full expression"
733// (e.g. CHECK_STREQ(Foo().c_str(), Bar().c_str())).
734
735#define CHECK_STREQ(s1, s2) CHECK_STROP(strcmp, ==, true, s1, s2)
736#define CHECK_STRNE(s1, s2) CHECK_STROP(strcmp, !=, false, s1, s2)
737#define CHECK_STRCASEEQ(s1, s2) CHECK_STROP(strcasecmp, ==, true, s1, s2)
738#define CHECK_STRCASENE(s1, s2) CHECK_STROP(strcasecmp, !=, false, s1, s2)
739
740#define CHECK_INDEX(I, A) CHECK(I < (sizeof(A) / sizeof(A[0])))
741#define CHECK_BOUND(B, A) CHECK(B <= (sizeof(A) / sizeof(A[0])))
742
743#define CHECK_DOUBLE_EQ(val1, val2) \
744 do { \
745 CHECK_LE((val1), (val2) + 0.000000000000001L); \
746 CHECK_GE((val1), (val2)-0.000000000000001L); \
747 } while (0)
748
749#define CHECK_NEAR(val1, val2, margin) \
750 do { \
751 CHECK_LE((val1), (val2) + (margin)); \
752 CHECK_GE((val1), (val2) - (margin)); \
753 } while (0)
754
755// perror()..googly style!
756//
757// PLOG() and PLOG_IF() and PCHECK() behave exactly like their LOG* and
758// CHECK equivalents with the addition that they postpend a description
759// of the current state of errno to their output lines.
760
761#define PLOG(severity) GOOGLE_PLOG(severity, 0).stream()
762
763#define GOOGLE_PLOG(severity, counter) \
764 google::ErrnoLogMessage(__FILE__, __LINE__, google::GLOG_##severity, \
765 counter, &google::LogMessage::SendToLog)
766
767#define PLOG_IF(severity, condition) \
768 static_cast<void>(0), \
769 !(condition) ? (void)0 : google::LogMessageVoidify() & PLOG(severity)
770
771// A CHECK() macro that postpends errno if the condition is false. E.g.
772//
773// if (poll(fds, nfds, timeout) == -1) { PCHECK(errno == EINTR); ... }
774#define PCHECK(condition) \
775 PLOG_IF(FATAL, GOOGLE_PREDICT_BRANCH_NOT_TAKEN(!(condition))) \
776 << "Check failed: " #condition " "
777
778// A CHECK() macro that lets you assert the success of a function that
779// returns -1 and sets errno in case of an error. E.g.
780//
781// CHECK_ERR(mkdir(path, 0700));
782//
783// or
784//
785// int fd = open(filename, flags); CHECK_ERR(fd) << ": open " << filename;
786#define CHECK_ERR(invocation) \
787 PLOG_IF(FATAL, GOOGLE_PREDICT_BRANCH_NOT_TAKEN((invocation) == -1)) \
788 << #invocation
789
790// Use macro expansion to create, for each use of LOG_EVERY_N(), static
791// variables with the __LINE__ expansion as part of the variable name.
792#define LOG_EVERY_N_VARNAME(base, line) LOG_EVERY_N_VARNAME_CONCAT(base, line)
793#define LOG_EVERY_N_VARNAME_CONCAT(base, line) base##line
794
795#define LOG_OCCURRENCES LOG_EVERY_N_VARNAME(occurrences_, __LINE__)
796#define LOG_OCCURRENCES_MOD_N LOG_EVERY_N_VARNAME(occurrences_mod_n_, __LINE__)
797
798#define SOME_KIND_OF_LOG_EVERY_N(severity, n, what_to_do) \
799 static int LOG_OCCURRENCES = 0, LOG_OCCURRENCES_MOD_N = 0; \
800 ++LOG_OCCURRENCES; \
801 if (++LOG_OCCURRENCES_MOD_N > n) LOG_OCCURRENCES_MOD_N -= n; \
802 if (LOG_OCCURRENCES_MOD_N == 1) \
803 google::LogMessage(__FILE__, __LINE__, google::GLOG_##severity, \
804 LOG_OCCURRENCES, &what_to_do) \
805 .stream()
806
807#define SOME_KIND_OF_LOG_IF_EVERY_N(severity, condition, n, what_to_do) \
808 static int LOG_OCCURRENCES = 0, LOG_OCCURRENCES_MOD_N = 0; \
809 ++LOG_OCCURRENCES; \
810 if (condition && \
811 ((LOG_OCCURRENCES_MOD_N = (LOG_OCCURRENCES_MOD_N + 1) % n) == (1 % n))) \
812 google::LogMessage(__FILE__, __LINE__, google::GLOG_##severity, \
813 LOG_OCCURRENCES, &what_to_do) \
814 .stream()
815
816#define SOME_KIND_OF_PLOG_EVERY_N(severity, n, what_to_do) \
817 static int LOG_OCCURRENCES = 0, LOG_OCCURRENCES_MOD_N = 0; \
818 ++LOG_OCCURRENCES; \
819 if (++LOG_OCCURRENCES_MOD_N > n) LOG_OCCURRENCES_MOD_N -= n; \
820 if (LOG_OCCURRENCES_MOD_N == 1) \
821 google::ErrnoLogMessage(__FILE__, __LINE__, google::GLOG_##severity, \
822 LOG_OCCURRENCES, &what_to_do) \
823 .stream()
824
825#define SOME_KIND_OF_LOG_FIRST_N(severity, n, what_to_do) \
826 static int LOG_OCCURRENCES = 0; \
827 if (LOG_OCCURRENCES <= n) ++LOG_OCCURRENCES; \
828 if (LOG_OCCURRENCES <= n) \
829 google::LogMessage(__FILE__, __LINE__, google::GLOG_##severity, \
830 LOG_OCCURRENCES, &what_to_do) \
831 .stream()
832
833namespace logging_internal {
834template <bool>
836struct CrashReason;
837} // namespace logging_internal
838
839#define LOG_EVERY_N(severity, n) \
840 SOME_KIND_OF_LOG_EVERY_N(severity, (n), google::LogMessage::SendToLog)
841
842#define SYSLOG_EVERY_N(severity, n) \
843 SOME_KIND_OF_LOG_EVERY_N(severity, (n), \
844 google::LogMessage::SendToSyslogAndLog)
845
846#define PLOG_EVERY_N(severity, n) \
847 SOME_KIND_OF_PLOG_EVERY_N(severity, (n), google::LogMessage::SendToLog)
848
849#define LOG_FIRST_N(severity, n) \
850 SOME_KIND_OF_LOG_FIRST_N(severity, (n), google::LogMessage::SendToLog)
851
852#define LOG_IF_EVERY_N(severity, condition, n) \
853 SOME_KIND_OF_LOG_IF_EVERY_N(severity, (condition), (n), \
854 google::LogMessage::SendToLog)
855
856// We want the special COUNTER value available for LOG_EVERY_X()'ed messages
858
859#ifdef _MSC_VER
860// wingdi.h defines ERROR to be 0. When we call LOG(ERROR), it gets
861// substituted with 0, and it expands to COMPACT_GOOGLE_LOG_0. To allow us
862// to keep using this syntax, we define this macro to do the same thing
863// as COMPACT_GOOGLE_LOG_ERROR.
864#define COMPACT_GOOGLE_LOG_0 COMPACT_GOOGLE_LOG_ERROR
865#define SYSLOG_0 SYSLOG_ERROR
866#define LOG_TO_STRING_0 LOG_TO_STRING_ERROR
867// Needed for LOG_IS_ON(ERROR).
868const LogSeverity GLOG_0 = GLOG_ERROR;
869#endif
870
871// Plus some debug-logging macros that get compiled to nothing for production
872
873#if DCHECK_IS_ON()
874
875#define DLOG(severity) LOG(severity)
876#define DVLOG(verboselevel) VLOG(verboselevel)
877#define DLOG_IF(severity, condition) LOG_IF(severity, condition)
878#define DLOG_EVERY_N(severity, n) LOG_EVERY_N(severity, n)
879#define DLOG_IF_EVERY_N(severity, condition, n) \
880 LOG_IF_EVERY_N(severity, condition, n)
881#define DLOG_ASSERT(condition) LOG_ASSERT(condition)
882
883// debug-only checking. executed if DCHECK_IS_ON().
884#define DCHECK(condition) CHECK(condition)
885#define DCHECK_EQ(val1, val2) CHECK_EQ(val1, val2)
886#define DCHECK_NE(val1, val2) CHECK_NE(val1, val2)
887#define DCHECK_LE(val1, val2) CHECK_LE(val1, val2)
888#define DCHECK_LT(val1, val2) CHECK_LT(val1, val2)
889#define DCHECK_GE(val1, val2) CHECK_GE(val1, val2)
890#define DCHECK_GT(val1, val2) CHECK_GT(val1, val2)
891#define DCHECK_NOTNULL(val) CHECK_NOTNULL(val)
892#define DCHECK_STREQ(str1, str2) CHECK_STREQ(str1, str2)
893#define DCHECK_STRCASEEQ(str1, str2) CHECK_STRCASEEQ(str1, str2)
894#define DCHECK_STRNE(str1, str2) CHECK_STRNE(str1, str2)
895#define DCHECK_STRCASENE(str1, str2) CHECK_STRCASENE(str1, str2)
896
897#else // !DCHECK_IS_ON()
898
899#define DLOG(severity) \
900 static_cast<void>(0), \
901 true ? (void)0 : google::LogMessageVoidify() & LOG(severity)
902
903#define DVLOG(verboselevel) \
904 static_cast<void>(0), (true || !VLOG_IS_ON(verboselevel)) \
905 ? (void)0 \
906 : google::LogMessageVoidify() & LOG(INFO)
907
908#define DLOG_IF(severity, condition) \
909 static_cast<void>(0), (true || !(condition)) \
910 ? (void)0 \
911 : google::LogMessageVoidify() & LOG(severity)
912
913#define DLOG_EVERY_N(severity, n) \
914 static_cast<void>(0), \
915 true ? (void)0 : google::LogMessageVoidify() & LOG(severity)
916
917#define DLOG_IF_EVERY_N(severity, condition, n) \
918 static_cast<void>(0), (true || !(condition)) \
919 ? (void)0 \
920 : google::LogMessageVoidify() & LOG(severity)
921
922#define DLOG_ASSERT(condition) \
923 static_cast<void>(0), true ? (void)0 : LOG_ASSERT(condition)
924
925// MSVC warning C4127: conditional expression is constant
926#define DCHECK(condition) \
927 GLOG_MSVC_PUSH_DISABLE_WARNING(4127) \
928 while (false) GLOG_MSVC_POP_WARNING() CHECK(condition)
929
930#define DCHECK_EQ(val1, val2) \
931 GLOG_MSVC_PUSH_DISABLE_WARNING(4127) \
932 while (false) GLOG_MSVC_POP_WARNING() CHECK_EQ(val1, val2)
933
934#define DCHECK_NE(val1, val2) \
935 GLOG_MSVC_PUSH_DISABLE_WARNING(4127) \
936 while (false) GLOG_MSVC_POP_WARNING() CHECK_NE(val1, val2)
937
938#define DCHECK_LE(val1, val2) \
939 GLOG_MSVC_PUSH_DISABLE_WARNING(4127) \
940 while (false) GLOG_MSVC_POP_WARNING() CHECK_LE(val1, val2)
941
942#define DCHECK_LT(val1, val2) \
943 GLOG_MSVC_PUSH_DISABLE_WARNING(4127) \
944 while (false) GLOG_MSVC_POP_WARNING() CHECK_LT(val1, val2)
945
946#define DCHECK_GE(val1, val2) \
947 GLOG_MSVC_PUSH_DISABLE_WARNING(4127) \
948 while (false) GLOG_MSVC_POP_WARNING() CHECK_GE(val1, val2)
949
950#define DCHECK_GT(val1, val2) \
951 GLOG_MSVC_PUSH_DISABLE_WARNING(4127) \
952 while (false) GLOG_MSVC_POP_WARNING() CHECK_GT(val1, val2)
953
954// You may see warnings in release mode if you don't use the return
955// value of DCHECK_NOTNULL. Please just use DCHECK for such cases.
956#define DCHECK_NOTNULL(val) (val)
957
958#define DCHECK_STREQ(str1, str2) \
959 GLOG_MSVC_PUSH_DISABLE_WARNING(4127) \
960 while (false) GLOG_MSVC_POP_WARNING() CHECK_STREQ(str1, str2)
961
962#define DCHECK_STRCASEEQ(str1, str2) \
963 GLOG_MSVC_PUSH_DISABLE_WARNING(4127) \
964 while (false) GLOG_MSVC_POP_WARNING() CHECK_STRCASEEQ(str1, str2)
965
966#define DCHECK_STRNE(str1, str2) \
967 GLOG_MSVC_PUSH_DISABLE_WARNING(4127) \
968 while (false) GLOG_MSVC_POP_WARNING() CHECK_STRNE(str1, str2)
969
970#define DCHECK_STRCASENE(str1, str2) \
971 GLOG_MSVC_PUSH_DISABLE_WARNING(4127) \
972 while (false) GLOG_MSVC_POP_WARNING() CHECK_STRCASENE(str1, str2)
973
974#endif // DCHECK_IS_ON()
975
976// Log only in verbose mode.
977
978#define VLOG(verboselevel) LOG_IF(INFO, VLOG_IS_ON(verboselevel))
979
980#define VLOG_IF(verboselevel, condition) \
981 LOG_IF(INFO, (condition) && VLOG_IS_ON(verboselevel))
982
983#define VLOG_EVERY_N(verboselevel, n) \
984 LOG_IF_EVERY_N(INFO, VLOG_IS_ON(verboselevel), n)
985
986#define VLOG_IF_EVERY_N(verboselevel, condition, n) \
987 LOG_IF_EVERY_N(INFO, (condition) && 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(NULL), 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 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 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 == NULL) {
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 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:78
std::ostream & operator<<(std::ostream &out, const google::DummyClassToDefineOperator &)
Definition: base/logging.h:535
#define ATTRIBUTE_NOINLINE
Definition: base/logging.h:54
#define GLOG_MSVC_PUSH_DISABLE_WARNING(n)
Definition: base/logging.h:52
ABSL_DECLARE_FLAG(bool, logtostderr)
#define DECLARE_CHECK_STROP_IMPL(func, expected)
Definition: base/logging.h:712
void FixFlagsAndEnvironmentForSwig()
Definition: base/logging.cc:61
#define GLOG_MSVC_POP_WARNING()
Definition: base/logging.h:53
#define ATTRIBUTE_NORETURN
Definition: base/logging.h:55
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 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
unsigned short uint16
unsigned int uint32
short int16
int64_t int64
uint64_t uint64
int LogSeverity
Definition: log_severity.h:22
#define GOOGLE_GLOG_DLL_DECL
Definition: file.cc:141
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 MakeCheckOpValueString(std::ostream *os, const char &v)
void InitGoogleLogging(const char *argv0)
DEFINE_CHECK_OP_IMPL(Check_EQ,==) DEFINE_CHECK_OP_IMPL(Check_NE
void LogAtLevel(int const severity, std::string const &msg)
void FlushLogFilesUnsafe(LogSeverity min_severity)
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)
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)
int posix_strerror_r(int err, char *buf, size_t len)
const T & GetReferenceableValue(const T &t)
Definition: base/logging.h:515
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:602
const int GLOG_ERROR
Definition: log_severity.h:25
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:395