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