blob: 8a26cbc46682319e759385dcf6255d303010d0fa [file] [log] [blame]
James Kuszmaulba0ac1a2022-08-12 16:29:30 -07001// Copyright (c) 2022, Google Inc.
Austin Schuh906616c2019-01-21 20:25:11 -08002// All rights reserved.
3//
4// Redistribution and use in source and binary forms, with or without
5// modification, are permitted provided that the following conditions are
6// met:
7//
8// * Redistributions of source code must retain the above copyright
9// notice, this list of conditions and the following disclaimer.
10// * Redistributions in binary form must reproduce the above
11// copyright notice, this list of conditions and the following disclaimer
12// in the documentation and/or other materials provided with the
13// distribution.
14// * Neither the name of Google Inc. nor the names of its
15// contributors may be used to endorse or promote products derived from
16// this software without specific prior written permission.
17//
18// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
19// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
20// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
21// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
22// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
23// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
24// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
25// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
26// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
27// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
28// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
29//
30// Author: Ray Sidney
31//
32// This file contains #include information about logging-related stuff.
33// Pretty much everybody needs to #include this file so that they can
34// log various happenings.
35//
James Kuszmaulba0ac1a2022-08-12 16:29:30 -070036#ifndef GLOG_LOGGING_H
37#define GLOG_LOGGING_H
Austin Schuh906616c2019-01-21 20:25:11 -080038
James Kuszmaulba0ac1a2022-08-12 16:29:30 -070039#if @ac_cv_cxx11_chrono@ && __cplusplus >= 201103L
40#include <chrono>
41#endif
42
43#include <cerrno>
44#include <cstddef>
45#include <cstdlib>
46#include <cstring>
47#include <ctime>
Austin Schuh906616c2019-01-21 20:25:11 -080048#include <iosfwd>
49#include <ostream>
50#include <sstream>
51#include <string>
52#if @ac_cv_have_unistd_h@
53# include <unistd.h>
54#endif
55#include <vector>
56
57#if defined(_MSC_VER)
58#define GLOG_MSVC_PUSH_DISABLE_WARNING(n) __pragma(warning(push)) \
59 __pragma(warning(disable:n))
60#define GLOG_MSVC_POP_WARNING() __pragma(warning(pop))
61#else
62#define GLOG_MSVC_PUSH_DISABLE_WARNING(n)
63#define GLOG_MSVC_POP_WARNING()
64#endif
65
James Kuszmaulba0ac1a2022-08-12 16:29:30 -070066#include <glog/platform.h>
67
68#if @ac_cv_have_glog_export@
69#include <glog/export.h>
Austin Schuh906616c2019-01-21 20:25:11 -080070#endif
71
72// We care a lot about number of bits things take up. Unfortunately,
73// systems define their bit-specific ints in a lot of different ways.
74// We use our own way, and have a typedef to get there.
75// Note: these commands below may look like "#if 1" or "#if 0", but
76// that's because they were constructed that way at ./configure time.
77// Look at logging.h.in to see how they're calculated (based on your config).
78#if @ac_cv_have_stdint_h@
79#include <stdint.h> // the normal place uint16_t is defined
80#endif
81#if @ac_cv_have_systypes_h@
82#include <sys/types.h> // the normal place u_int16_t is defined
83#endif
84#if @ac_cv_have_inttypes_h@
85#include <inttypes.h> // a third place for uint16_t or u_int16_t
86#endif
87
88#if @ac_cv_have_libgflags@
89#include <gflags/gflags.h>
90#endif
91
James Kuszmaulba0ac1a2022-08-12 16:29:30 -070092#if @ac_cv_cxx11_atomic@ && __cplusplus >= 201103L
93#include <atomic>
94#elif defined(GLOG_OS_WINDOWS)
95#include <Windows.h>
96#endif
97
Austin Schuh906616c2019-01-21 20:25:11 -080098@ac_google_start_namespace@
99
James Kuszmaulba0ac1a2022-08-12 16:29:30 -0700100#if @ac_cv_have_stdint_h@ // the C99 format
Austin Schuh906616c2019-01-21 20:25:11 -0800101typedef int32_t int32;
102typedef uint32_t uint32;
103typedef int64_t int64;
104typedef uint64_t uint64;
105#elif @ac_cv_have_u_int16_t@ // the BSD format
106typedef int32_t int32;
107typedef u_int32_t uint32;
108typedef int64_t int64;
109typedef u_int64_t uint64;
110#elif @ac_cv_have___uint16@ // the windows (vc7) format
111typedef __int32 int32;
112typedef unsigned __int32 uint32;
113typedef __int64 int64;
114typedef unsigned __int64 uint64;
115#else
116#error Do not know how to define a 32-bit integer quantity on your system
117#endif
118
James Kuszmaulba0ac1a2022-08-12 16:29:30 -0700119#if !(@ac_cv_have_ssize_t@)
120typedef ptrdiff_t ssize_t;
121#endif
122
123#if !(@ac_cv_have_mode_t@)
124typedef int mode_t;
125#endif
126
127typedef double WallTime;
128
129struct GLOG_EXPORT LogMessageTime {
130 LogMessageTime();
131 LogMessageTime(std::tm t);
132 LogMessageTime(std::time_t timestamp, WallTime now);
133
134 const time_t& timestamp() const { return timestamp_; }
135 const int& sec() const { return time_struct_.tm_sec; }
136 const int32_t& usec() const { return usecs_; }
137 const int&(min)() const { return time_struct_.tm_min; }
138 const int& hour() const { return time_struct_.tm_hour; }
139 const int& day() const { return time_struct_.tm_mday; }
140 const int& month() const { return time_struct_.tm_mon; }
141 const int& year() const { return time_struct_.tm_year; }
142 const int& dayOfWeek() const { return time_struct_.tm_wday; }
143 const int& dayInYear() const { return time_struct_.tm_yday; }
144 const int& dst() const { return time_struct_.tm_isdst; }
145 const long int& gmtoff() const { return gmtoffset_; }
146 const std::tm& tm() const { return time_struct_; }
147
148 private:
149 void init(const std::tm& t, std::time_t timestamp, WallTime now);
150 std::tm time_struct_; // Time of creation of LogMessage
151 time_t timestamp_; // Time of creation of LogMessage in seconds
152 int32_t usecs_; // Time of creation of LogMessage - microseconds part
153 long int gmtoffset_;
154
155 void CalcGmtOffset();
156};
157
158#ifdef GLOG_CUSTOM_PREFIX_SUPPORT
159struct LogMessageInfo {
160 explicit LogMessageInfo(const char* const severity_,
161 const char* const filename_,
162 const int& line_number_,
163 const int& thread_id_,
164 const LogMessageTime& time_):
165 severity(severity_), filename(filename_), line_number(line_number_),
166 thread_id(thread_id_), time(time_)
167 {}
168
169 const char* const severity;
170 const char* const filename;
171 const int &line_number;
172 const int &thread_id;
173 const LogMessageTime& time;
174};
175
176typedef void(*CustomPrefixCallback)(std::ostream& s, const LogMessageInfo& l, void* data);
177
178#endif
179
Austin Schuh906616c2019-01-21 20:25:11 -0800180@ac_google_end_namespace@
181
James Kuszmaulba0ac1a2022-08-12 16:29:30 -0700182
Austin Schuh906616c2019-01-21 20:25:11 -0800183// The global value of GOOGLE_STRIP_LOG. All the messages logged to
184// LOG(XXX) with severity less than GOOGLE_STRIP_LOG will not be displayed.
185// If it can be determined at compile time that the message will not be
186// printed, the statement will be compiled out.
187//
188// Example: to strip out all INFO and WARNING messages, use the value
189// of 2 below. To make an exception for WARNING messages from a single
190// file, add "#define GOOGLE_STRIP_LOG 1" to that file _before_ including
191// base/logging.h
192#ifndef GOOGLE_STRIP_LOG
193#define GOOGLE_STRIP_LOG 0
194#endif
195
196// GCC can be told that a certain branch is not likely to be taken (for
197// instance, a CHECK failure), and use that information in static analysis.
198// Giving it this information can help it optimize for the common case in
199// the absence of better information (ie. -fprofile-arcs).
200//
201#ifndef GOOGLE_PREDICT_BRANCH_NOT_TAKEN
202#if @ac_cv_have___builtin_expect@
203#define GOOGLE_PREDICT_BRANCH_NOT_TAKEN(x) (__builtin_expect(x, 0))
204#else
205#define GOOGLE_PREDICT_BRANCH_NOT_TAKEN(x) x
206#endif
207#endif
208
209#ifndef GOOGLE_PREDICT_FALSE
210#if @ac_cv_have___builtin_expect@
211#define GOOGLE_PREDICT_FALSE(x) (__builtin_expect(x, 0))
212#else
213#define GOOGLE_PREDICT_FALSE(x) x
214#endif
215#endif
216
217#ifndef GOOGLE_PREDICT_TRUE
218#if @ac_cv_have___builtin_expect@
219#define GOOGLE_PREDICT_TRUE(x) (__builtin_expect(!!(x), 1))
220#else
221#define GOOGLE_PREDICT_TRUE(x) x
222#endif
223#endif
224
225
226// Make a bunch of macros for logging. The way to log things is to stream
227// things to LOG(<a particular severity level>). E.g.,
228//
229// LOG(INFO) << "Found " << num_cookies << " cookies";
230//
231// You can capture log messages in a string, rather than reporting them
232// immediately:
233//
234// vector<string> errors;
235// LOG_STRING(ERROR, &errors) << "Couldn't parse cookie #" << cookie_num;
236//
237// This pushes back the new error onto 'errors'; if given a NULL pointer,
238// it reports the error via LOG(ERROR).
239//
240// You can also do conditional logging:
241//
242// LOG_IF(INFO, num_cookies > 10) << "Got lots of cookies";
243//
244// You can also do occasional logging (log every n'th occurrence of an
245// event):
246//
247// LOG_EVERY_N(INFO, 10) << "Got the " << google::COUNTER << "th cookie";
248//
249// The above will cause log messages to be output on the 1st, 11th, 21st, ...
250// times it is executed. Note that the special google::COUNTER value is used
251// to identify which repetition is happening.
252//
253// You can also do occasional conditional logging (log every n'th
254// occurrence of an event, when condition is satisfied):
255//
256// LOG_IF_EVERY_N(INFO, (size > 1024), 10) << "Got the " << google::COUNTER
257// << "th big cookie";
258//
259// You can log messages the first N times your code executes a line. E.g.
260//
261// LOG_FIRST_N(INFO, 20) << "Got the " << google::COUNTER << "th cookie";
262//
263// Outputs log messages for the first 20 times it is executed.
264//
265// Analogous SYSLOG, SYSLOG_IF, and SYSLOG_EVERY_N macros are available.
266// These log to syslog as well as to the normal logs. If you use these at
267// all, you need to be aware that syslog can drastically reduce performance,
268// especially if it is configured for remote logging! Don't use these
269// unless you fully understand this and have a concrete need to use them.
270// Even then, try to minimize your use of them.
271//
272// There are also "debug mode" logging macros like the ones above:
273//
274// DLOG(INFO) << "Found cookies";
275//
276// DLOG_IF(INFO, num_cookies > 10) << "Got lots of cookies";
277//
278// DLOG_EVERY_N(INFO, 10) << "Got the " << google::COUNTER << "th cookie";
279//
280// All "debug mode" logging is compiled away to nothing for non-debug mode
281// compiles.
282//
283// We also have
284//
285// LOG_ASSERT(assertion);
286// DLOG_ASSERT(assertion);
287//
288// which is syntactic sugar for {,D}LOG_IF(FATAL, assert fails) << assertion;
289//
290// There are "verbose level" logging macros. They look like
291//
292// VLOG(1) << "I'm printed when you run the program with --v=1 or more";
293// VLOG(2) << "I'm printed when you run the program with --v=2 or more";
294//
295// These always log at the INFO log level (when they log at all).
296// The verbose logging can also be turned on module-by-module. For instance,
297// --vmodule=mapreduce=2,file=1,gfs*=3 --v=0
298// will cause:
299// a. VLOG(2) and lower messages to be printed from mapreduce.{h,cc}
300// b. VLOG(1) and lower messages to be printed from file.{h,cc}
301// c. VLOG(3) and lower messages to be printed from files prefixed with "gfs"
302// d. VLOG(0) and lower messages to be printed from elsewhere
303//
304// The wildcarding functionality shown by (c) supports both '*' (match
305// 0 or more characters) and '?' (match any single character) wildcards.
306//
307// There's also VLOG_IS_ON(n) "verbose level" condition macro. To be used as
308//
309// if (VLOG_IS_ON(2)) {
310// // do some logging preparation and logging
311// // that can't be accomplished with just VLOG(2) << ...;
312// }
313//
314// There are also VLOG_IF, VLOG_EVERY_N and VLOG_IF_EVERY_N "verbose level"
315// condition macros for sample cases, when some extra computation and
316// preparation for logs is not needed.
317// VLOG_IF(1, (size > 1024))
318// << "I'm printed when size is more than 1024 and when you run the "
319// "program with --v=1 or more";
320// VLOG_EVERY_N(1, 10)
321// << "I'm printed every 10th occurrence, and when you run the program "
322// "with --v=1 or more. Present occurence is " << google::COUNTER;
323// VLOG_IF_EVERY_N(1, (size > 1024), 10)
324// << "I'm printed on every 10th occurence of case when size is more "
325// " than 1024, when you run the program with --v=1 or more. ";
326// "Present occurence is " << google::COUNTER;
327//
328// The supported severity levels for macros that allow you to specify one
329// are (in increasing order of severity) INFO, WARNING, ERROR, and FATAL.
330// Note that messages of a given severity are logged not only in the
331// logfile for that severity, but also in all logfiles of lower severity.
332// E.g., a message of severity FATAL will be logged to the logfiles of
333// severity FATAL, ERROR, WARNING, and INFO.
334//
335// There is also the special severity of DFATAL, which logs FATAL in
336// debug mode, ERROR in normal mode.
337//
338// Very important: logging a message at the FATAL severity level causes
339// the program to terminate (after the message is logged).
340//
341// Unless otherwise specified, logs will be written to the filename
342// "<program name>.<hostname>.<user name>.log.<severity level>.", followed
343// by the date, time, and pid (you can't prevent the date, time, and pid
344// from being in the filename).
345//
346// The logging code takes two flags:
347// --v=# set the verbose level
348// --logtostderr log all the messages to stderr instead of to logfiles
349
350// LOG LINE PREFIX FORMAT
351//
352// Log lines have this form:
353//
James Kuszmaulba0ac1a2022-08-12 16:29:30 -0700354// Lyyyymmdd hh:mm:ss.uuuuuu threadid file:line] msg...
Austin Schuh906616c2019-01-21 20:25:11 -0800355//
356// where the fields are defined as follows:
357//
358// L A single character, representing the log level
359// (eg 'I' for INFO)
James Kuszmaulba0ac1a2022-08-12 16:29:30 -0700360// yyyy The year
Austin Schuh906616c2019-01-21 20:25:11 -0800361// mm The month (zero padded; ie May is '05')
362// dd The day (zero padded)
363// hh:mm:ss.uuuuuu Time in hours, minutes and fractional seconds
364// threadid The space-padded thread ID as returned by GetTID()
365// (this matches the PID on Linux)
366// file The file name
367// line The line number
368// msg The user-supplied message
369//
370// Example:
371//
372// I1103 11:57:31.739339 24395 google.cc:2341] Command line: ./some_prog
373// I1103 11:57:31.739403 24395 google.cc:2342] Process id 24395
374//
375// NOTE: although the microseconds are useful for comparing events on
376// a single machine, clocks on different machines may not be well
377// synchronized. Hence, use caution when comparing the low bits of
378// timestamps from different machines.
379
James Kuszmaulba0ac1a2022-08-12 16:29:30 -0700380#pragma push_macro("DECLARE_VARIABLE")
381#pragma push_macro("DECLARE_bool")
382#pragma push_macro("DECLARE_string")
383#pragma push_macro("DECLARE_int32")
384#pragma push_macro("DECLARE_uint32")
385
386#ifdef DECLARE_VARIABLE
387#undef DECLARE_VARIABLE
388#endif
389
390#ifdef DECLARE_bool
391#undef DECLARE_bool
392#endif
393
394#ifdef DECLARE_string
395#undef DECLARE_string
396#endif
397
398#ifdef DECLARE_int32
399#undef DECLARE_int32
400#endif
401
402#ifdef DECLARE_uint32
403#undef DECLARE_uint32
404#endif
405
Austin Schuh906616c2019-01-21 20:25:11 -0800406#ifndef DECLARE_VARIABLE
Austin Schuh906616c2019-01-21 20:25:11 -0800407#define DECLARE_VARIABLE(type, shorttype, name, tn) \
408 namespace fL##shorttype { \
James Kuszmaulba0ac1a2022-08-12 16:29:30 -0700409 extern GLOG_EXPORT type FLAGS_##name; \
Austin Schuh906616c2019-01-21 20:25:11 -0800410 } \
411 using fL##shorttype::FLAGS_##name
412
413// bool specialization
414#define DECLARE_bool(name) \
415 DECLARE_VARIABLE(bool, B, name, bool)
416
417// int32 specialization
418#define DECLARE_int32(name) \
419 DECLARE_VARIABLE(@ac_google_namespace@::int32, I, name, int32)
420
James Kuszmaulba0ac1a2022-08-12 16:29:30 -0700421#if !defined(DECLARE_uint32)
422// uint32 specialization
423#define DECLARE_uint32(name) \
424 DECLARE_VARIABLE(@ac_google_namespace@::uint32, U, name, uint32)
425#endif // !defined(DECLARE_uint32) && !(@ac_cv_have_libgflags@)
426
Austin Schuh906616c2019-01-21 20:25:11 -0800427// Special case for string, because we have to specify the namespace
428// std::string, which doesn't play nicely with our FLAG__namespace hackery.
429#define DECLARE_string(name) \
430 namespace fLS { \
James Kuszmaulba0ac1a2022-08-12 16:29:30 -0700431 extern GLOG_EXPORT std::string& FLAGS_##name; \
Austin Schuh906616c2019-01-21 20:25:11 -0800432 } \
433 using fLS::FLAGS_##name
434#endif
435
James Kuszmaulba0ac1a2022-08-12 16:29:30 -0700436// Set whether appending a timestamp to the log file name
437DECLARE_bool(timestamp_in_logfile_name);
438
439// Set whether log messages go to stdout instead of logfiles
440DECLARE_bool(logtostdout);
441
442// Set color messages logged to stdout (if supported by terminal).
443DECLARE_bool(colorlogtostdout);
444
Austin Schuh906616c2019-01-21 20:25:11 -0800445// Set whether log messages go to stderr instead of logfiles
446DECLARE_bool(logtostderr);
447
448// Set whether log messages go to stderr in addition to logfiles.
449DECLARE_bool(alsologtostderr);
450
451// Set color messages logged to stderr (if supported by terminal).
452DECLARE_bool(colorlogtostderr);
453
454// Log messages at a level >= this flag are automatically sent to
455// stderr in addition to log files.
456DECLARE_int32(stderrthreshold);
457
458// Set whether the log prefix should be prepended to each line of output.
459DECLARE_bool(log_prefix);
460
James Kuszmaulba0ac1a2022-08-12 16:29:30 -0700461// Set whether the year should be included in the log prefix.
462DECLARE_bool(log_year_in_prefix);
463
Austin Schuh906616c2019-01-21 20:25:11 -0800464// Log messages at a level <= this flag are buffered.
465// Log messages at a higher level are flushed immediately.
466DECLARE_int32(logbuflevel);
467
468// Sets the maximum number of seconds which logs may be buffered for.
469DECLARE_int32(logbufsecs);
470
471// Log suppression level: messages logged at a lower level than this
472// are suppressed.
473DECLARE_int32(minloglevel);
474
475// If specified, logfiles are written into this directory instead of the
476// default logging directory.
477DECLARE_string(log_dir);
478
479// Set the log file mode.
480DECLARE_int32(logfile_mode);
481
482// Sets the path of the directory into which to put additional links
483// to the log files.
484DECLARE_string(log_link);
485
486DECLARE_int32(v); // in vlog_is_on.cc
487
James Kuszmaulba0ac1a2022-08-12 16:29:30 -0700488DECLARE_string(vmodule); // also in vlog_is_on.cc
489
Austin Schuh906616c2019-01-21 20:25:11 -0800490// Sets the maximum log file size (in MB).
James Kuszmaulba0ac1a2022-08-12 16:29:30 -0700491DECLARE_uint32(max_log_size);
Austin Schuh906616c2019-01-21 20:25:11 -0800492
493// Sets whether to avoid logging to the disk if the disk is full.
494DECLARE_bool(stop_logging_if_full_disk);
495
James Kuszmaulba0ac1a2022-08-12 16:29:30 -0700496// Use UTC time for logging
497DECLARE_bool(log_utc_time);
Austin Schuh906616c2019-01-21 20:25:11 -0800498
499// Log messages below the GOOGLE_STRIP_LOG level will be compiled away for
500// security reasons. See LOG(severtiy) below.
501
502// A few definitions of macros that don't generate much code. Since
503// LOG(INFO) and its ilk are used all over our code, it's
504// better to have compact code for these operations.
505
506#if GOOGLE_STRIP_LOG == 0
507#define COMPACT_GOOGLE_LOG_INFO @ac_google_namespace@::LogMessage( \
508 __FILE__, __LINE__)
509#define LOG_TO_STRING_INFO(message) @ac_google_namespace@::LogMessage( \
510 __FILE__, __LINE__, @ac_google_namespace@::GLOG_INFO, message)
511#else
512#define COMPACT_GOOGLE_LOG_INFO @ac_google_namespace@::NullStream()
513#define LOG_TO_STRING_INFO(message) @ac_google_namespace@::NullStream()
514#endif
515
516#if GOOGLE_STRIP_LOG <= 1
517#define COMPACT_GOOGLE_LOG_WARNING @ac_google_namespace@::LogMessage( \
518 __FILE__, __LINE__, @ac_google_namespace@::GLOG_WARNING)
519#define LOG_TO_STRING_WARNING(message) @ac_google_namespace@::LogMessage( \
520 __FILE__, __LINE__, @ac_google_namespace@::GLOG_WARNING, message)
521#else
522#define COMPACT_GOOGLE_LOG_WARNING @ac_google_namespace@::NullStream()
523#define LOG_TO_STRING_WARNING(message) @ac_google_namespace@::NullStream()
524#endif
525
526#if GOOGLE_STRIP_LOG <= 2
527#define COMPACT_GOOGLE_LOG_ERROR @ac_google_namespace@::LogMessage( \
528 __FILE__, __LINE__, @ac_google_namespace@::GLOG_ERROR)
529#define LOG_TO_STRING_ERROR(message) @ac_google_namespace@::LogMessage( \
530 __FILE__, __LINE__, @ac_google_namespace@::GLOG_ERROR, message)
531#else
532#define COMPACT_GOOGLE_LOG_ERROR @ac_google_namespace@::NullStream()
533#define LOG_TO_STRING_ERROR(message) @ac_google_namespace@::NullStream()
534#endif
535
536#if GOOGLE_STRIP_LOG <= 3
537#define COMPACT_GOOGLE_LOG_FATAL @ac_google_namespace@::LogMessageFatal( \
538 __FILE__, __LINE__)
539#define LOG_TO_STRING_FATAL(message) @ac_google_namespace@::LogMessage( \
540 __FILE__, __LINE__, @ac_google_namespace@::GLOG_FATAL, message)
541#else
542#define COMPACT_GOOGLE_LOG_FATAL @ac_google_namespace@::NullStreamFatal()
543#define LOG_TO_STRING_FATAL(message) @ac_google_namespace@::NullStreamFatal()
544#endif
545
546#if defined(NDEBUG) && !defined(DCHECK_ALWAYS_ON)
547#define DCHECK_IS_ON() 0
548#else
549#define DCHECK_IS_ON() 1
550#endif
551
552// For DFATAL, we want to use LogMessage (as opposed to
553// LogMessageFatal), to be consistent with the original behavior.
554#if !DCHECK_IS_ON()
555#define COMPACT_GOOGLE_LOG_DFATAL COMPACT_GOOGLE_LOG_ERROR
556#elif GOOGLE_STRIP_LOG <= 3
557#define COMPACT_GOOGLE_LOG_DFATAL @ac_google_namespace@::LogMessage( \
558 __FILE__, __LINE__, @ac_google_namespace@::GLOG_FATAL)
559#else
560#define COMPACT_GOOGLE_LOG_DFATAL @ac_google_namespace@::NullStreamFatal()
561#endif
562
563#define GOOGLE_LOG_INFO(counter) @ac_google_namespace@::LogMessage(__FILE__, __LINE__, @ac_google_namespace@::GLOG_INFO, counter, &@ac_google_namespace@::LogMessage::SendToLog)
564#define SYSLOG_INFO(counter) \
565 @ac_google_namespace@::LogMessage(__FILE__, __LINE__, @ac_google_namespace@::GLOG_INFO, counter, \
566 &@ac_google_namespace@::LogMessage::SendToSyslogAndLog)
567#define GOOGLE_LOG_WARNING(counter) \
568 @ac_google_namespace@::LogMessage(__FILE__, __LINE__, @ac_google_namespace@::GLOG_WARNING, counter, \
569 &@ac_google_namespace@::LogMessage::SendToLog)
570#define SYSLOG_WARNING(counter) \
571 @ac_google_namespace@::LogMessage(__FILE__, __LINE__, @ac_google_namespace@::GLOG_WARNING, counter, \
572 &@ac_google_namespace@::LogMessage::SendToSyslogAndLog)
573#define GOOGLE_LOG_ERROR(counter) \
574 @ac_google_namespace@::LogMessage(__FILE__, __LINE__, @ac_google_namespace@::GLOG_ERROR, counter, \
575 &@ac_google_namespace@::LogMessage::SendToLog)
576#define SYSLOG_ERROR(counter) \
577 @ac_google_namespace@::LogMessage(__FILE__, __LINE__, @ac_google_namespace@::GLOG_ERROR, counter, \
578 &@ac_google_namespace@::LogMessage::SendToSyslogAndLog)
579#define GOOGLE_LOG_FATAL(counter) \
580 @ac_google_namespace@::LogMessage(__FILE__, __LINE__, @ac_google_namespace@::GLOG_FATAL, counter, \
581 &@ac_google_namespace@::LogMessage::SendToLog)
582#define SYSLOG_FATAL(counter) \
583 @ac_google_namespace@::LogMessage(__FILE__, __LINE__, @ac_google_namespace@::GLOG_FATAL, counter, \
584 &@ac_google_namespace@::LogMessage::SendToSyslogAndLog)
585#define GOOGLE_LOG_DFATAL(counter) \
586 @ac_google_namespace@::LogMessage(__FILE__, __LINE__, @ac_google_namespace@::DFATAL_LEVEL, counter, \
587 &@ac_google_namespace@::LogMessage::SendToLog)
588#define SYSLOG_DFATAL(counter) \
589 @ac_google_namespace@::LogMessage(__FILE__, __LINE__, @ac_google_namespace@::DFATAL_LEVEL, counter, \
590 &@ac_google_namespace@::LogMessage::SendToSyslogAndLog)
591
592#if defined(WIN32) || defined(_WIN32) || defined(__WIN32__) || defined(__CYGWIN__) || defined(__CYGWIN32__)
593// A very useful logging macro to log windows errors:
594#define LOG_SYSRESULT(result) \
595 if (FAILED(HRESULT_FROM_WIN32(result))) { \
596 LPSTR message = NULL; \
597 LPSTR msg = reinterpret_cast<LPSTR>(&message); \
598 DWORD message_length = FormatMessageA(FORMAT_MESSAGE_ALLOCATE_BUFFER | \
James Kuszmaulba0ac1a2022-08-12 16:29:30 -0700599 FORMAT_MESSAGE_FROM_SYSTEM | \
600 FORMAT_MESSAGE_IGNORE_INSERTS, \
Austin Schuh906616c2019-01-21 20:25:11 -0800601 0, result, 0, msg, 100, NULL); \
602 if (message_length > 0) { \
603 @ac_google_namespace@::LogMessage(__FILE__, __LINE__, @ac_google_namespace@::GLOG_ERROR, 0, \
604 &@ac_google_namespace@::LogMessage::SendToLog).stream() \
605 << reinterpret_cast<const char*>(message); \
606 LocalFree(message); \
607 } \
608 }
609#endif
610
611// We use the preprocessor's merging operator, "##", so that, e.g.,
612// LOG(INFO) becomes the token GOOGLE_LOG_INFO. There's some funny
613// subtle difference between ostream member streaming functions (e.g.,
614// ostream::operator<<(int) and ostream non-member streaming functions
615// (e.g., ::operator<<(ostream&, string&): it turns out that it's
616// impossible to stream something like a string directly to an unnamed
617// ostream. We employ a neat hack by calling the stream() member
618// function of LogMessage which seems to avoid the problem.
619#define LOG(severity) COMPACT_GOOGLE_LOG_ ## severity.stream()
620#define SYSLOG(severity) SYSLOG_ ## severity(0).stream()
621
622@ac_google_start_namespace@
623
624// They need the definitions of integer types.
James Kuszmaulba0ac1a2022-08-12 16:29:30 -0700625#include <glog/log_severity.h>
626#include <glog/vlog_is_on.h>
Austin Schuh906616c2019-01-21 20:25:11 -0800627
628// Initialize google's logging library. You will see the program name
629// specified by argv0 in log outputs.
James Kuszmaulba0ac1a2022-08-12 16:29:30 -0700630GLOG_EXPORT void InitGoogleLogging(const char* argv0);
631
632#ifdef GLOG_CUSTOM_PREFIX_SUPPORT
633GLOG_EXPORT void InitGoogleLogging(const char* argv0,
634 CustomPrefixCallback prefix_callback,
635 void* prefix_callback_data = NULL);
636#endif
637
638// Check if google's logging library has been initialized.
639GLOG_EXPORT bool IsGoogleLoggingInitialized();
Austin Schuh906616c2019-01-21 20:25:11 -0800640
641// Shutdown google's logging library.
James Kuszmaulba0ac1a2022-08-12 16:29:30 -0700642GLOG_EXPORT void ShutdownGoogleLogging();
643
644#if defined(__GNUC__)
645typedef void (*logging_fail_func_t)() __attribute__((noreturn));
646#else
647typedef void (*logging_fail_func_t)();
648#endif
Austin Schuh906616c2019-01-21 20:25:11 -0800649
650// Install a function which will be called after LOG(FATAL).
James Kuszmaulba0ac1a2022-08-12 16:29:30 -0700651GLOG_EXPORT void InstallFailureFunction(logging_fail_func_t fail_func);
652
653// Enable/Disable old log cleaner.
654GLOG_EXPORT void EnableLogCleaner(unsigned int overdue_days);
655GLOG_EXPORT void DisableLogCleaner();
656GLOG_EXPORT void SetApplicationFingerprint(const std::string& fingerprint);
Austin Schuh906616c2019-01-21 20:25:11 -0800657
658class LogSink; // defined below
659
660// If a non-NULL sink pointer is given, we push this message to that sink.
661// For LOG_TO_SINK we then do normal LOG(severity) logging as well.
662// This is useful for capturing messages and passing/storing them
663// somewhere more specific than the global log of the process.
664// Argument types:
665// LogSink* sink;
666// LogSeverity severity;
667// The cast is to disambiguate NULL arguments.
668#define LOG_TO_SINK(sink, severity) \
669 @ac_google_namespace@::LogMessage( \
670 __FILE__, __LINE__, \
671 @ac_google_namespace@::GLOG_ ## severity, \
672 static_cast<@ac_google_namespace@::LogSink*>(sink), true).stream()
673#define LOG_TO_SINK_BUT_NOT_TO_LOGFILE(sink, severity) \
674 @ac_google_namespace@::LogMessage( \
675 __FILE__, __LINE__, \
676 @ac_google_namespace@::GLOG_ ## severity, \
677 static_cast<@ac_google_namespace@::LogSink*>(sink), false).stream()
678
679// If a non-NULL string pointer is given, we write this message to that string.
680// We then do normal LOG(severity) logging as well.
681// This is useful for capturing messages and storing them somewhere more
682// specific than the global log of the process.
683// Argument types:
684// string* message;
685// LogSeverity severity;
686// The cast is to disambiguate NULL arguments.
687// NOTE: LOG(severity) expands to LogMessage().stream() for the specified
688// severity.
689#define LOG_TO_STRING(severity, message) \
James Kuszmaulba0ac1a2022-08-12 16:29:30 -0700690 LOG_TO_STRING_##severity(static_cast<std::string*>(message)).stream()
Austin Schuh906616c2019-01-21 20:25:11 -0800691
692// If a non-NULL pointer is given, we push the message onto the end
693// of a vector of strings; otherwise, we report it with LOG(severity).
694// This is handy for capturing messages and perhaps passing them back
695// to the caller, rather than reporting them immediately.
696// Argument types:
697// LogSeverity severity;
698// vector<string> *outvec;
699// The cast is to disambiguate NULL arguments.
700#define LOG_STRING(severity, outvec) \
701 LOG_TO_STRING_##severity(static_cast<std::vector<std::string>*>(outvec)).stream()
702
James Kuszmaulba0ac1a2022-08-12 16:29:30 -0700703#define LOG_IF(severity, condition) if(condition) LOG(severity)
704#define SYSLOG_IF(severity, condition) if(condition) SYSLOG(severity)
Austin Schuh906616c2019-01-21 20:25:11 -0800705
706#define LOG_ASSERT(condition) \
707 LOG_IF(FATAL, !(condition)) << "Assert failed: " #condition
708#define SYSLOG_ASSERT(condition) \
709 SYSLOG_IF(FATAL, !(condition)) << "Assert failed: " #condition
710
711// CHECK dies with a fatal error if condition is not true. It is *not*
712// controlled by DCHECK_IS_ON(), so the check will be executed regardless of
713// compilation mode. Therefore, it is safe to do things like:
714// CHECK(fp->Write(x) == 4)
715#define CHECK(condition) \
716 LOG_IF(FATAL, GOOGLE_PREDICT_BRANCH_NOT_TAKEN(!(condition))) \
717 << "Check failed: " #condition " "
718
719// A container for a string pointer which can be evaluated to a bool -
720// true iff the pointer is NULL.
721struct CheckOpString {
722 CheckOpString(std::string* str) : str_(str) { }
723 // No destructor: if str_ is non-NULL, we're about to LOG(FATAL),
724 // so there's no point in cleaning up str_.
725 operator bool() const {
726 return GOOGLE_PREDICT_BRANCH_NOT_TAKEN(str_ != NULL);
727 }
728 std::string* str_;
729};
730
731// Function is overloaded for integral types to allow static const
732// integrals declared in classes and not defined to be used as arguments to
733// CHECK* macros. It's not encouraged though.
734template <class T>
735inline const T& GetReferenceableValue(const T& t) { return t; }
736inline char GetReferenceableValue(char t) { return t; }
737inline unsigned char GetReferenceableValue(unsigned char t) { return t; }
738inline signed char GetReferenceableValue(signed char t) { return t; }
739inline short GetReferenceableValue(short t) { return t; }
740inline unsigned short GetReferenceableValue(unsigned short t) { return t; }
741inline int GetReferenceableValue(int t) { return t; }
742inline unsigned int GetReferenceableValue(unsigned int t) { return t; }
743inline long GetReferenceableValue(long t) { return t; }
744inline unsigned long GetReferenceableValue(unsigned long t) { return t; }
James Kuszmaulba0ac1a2022-08-12 16:29:30 -0700745#if __cplusplus >= 201103L
Austin Schuh906616c2019-01-21 20:25:11 -0800746inline long long GetReferenceableValue(long long t) { return t; }
747inline unsigned long long GetReferenceableValue(unsigned long long t) {
748 return t;
749}
James Kuszmaulba0ac1a2022-08-12 16:29:30 -0700750#endif
Austin Schuh906616c2019-01-21 20:25:11 -0800751
752// This is a dummy class to define the following operator.
753struct DummyClassToDefineOperator {};
754
755@ac_google_end_namespace@
756
757// Define global operator<< to declare using ::operator<<.
758// This declaration will allow use to use CHECK macros for user
759// defined classes which have operator<< (e.g., stl_logging.h).
760inline std::ostream& operator<<(
761 std::ostream& out, const google::DummyClassToDefineOperator&) {
762 return out;
763}
764
765@ac_google_start_namespace@
766
767// This formats a value for a failing CHECK_XX statement. Ordinarily,
768// it uses the definition for operator<<, with a few special cases below.
769template <typename T>
770inline void MakeCheckOpValueString(std::ostream* os, const T& v) {
771 (*os) << v;
772}
773
774// Overrides for char types provide readable values for unprintable
775// characters.
James Kuszmaulba0ac1a2022-08-12 16:29:30 -0700776template <> GLOG_EXPORT
Austin Schuh906616c2019-01-21 20:25:11 -0800777void MakeCheckOpValueString(std::ostream* os, const char& v);
James Kuszmaulba0ac1a2022-08-12 16:29:30 -0700778template <> GLOG_EXPORT
Austin Schuh906616c2019-01-21 20:25:11 -0800779void MakeCheckOpValueString(std::ostream* os, const signed char& v);
James Kuszmaulba0ac1a2022-08-12 16:29:30 -0700780template <> GLOG_EXPORT
Austin Schuh906616c2019-01-21 20:25:11 -0800781void MakeCheckOpValueString(std::ostream* os, const unsigned char& v);
782
James Kuszmaulba0ac1a2022-08-12 16:29:30 -0700783// This is required because nullptr is only present in c++ 11 and later.
784#if @ac_cv_cxx11_nullptr_t@ && __cplusplus >= 201103L
785// Provide printable value for nullptr_t
786template <> GLOG_EXPORT
787void MakeCheckOpValueString(std::ostream* os, const std::nullptr_t& v);
788#endif
789
Austin Schuh906616c2019-01-21 20:25:11 -0800790// Build the error message string. Specify no inlining for code size.
791template <typename T1, typename T2>
792std::string* MakeCheckOpString(const T1& v1, const T2& v2, const char* exprtext)
793 @ac_cv___attribute___noinline@;
794
795namespace base {
796namespace internal {
797
798// If "s" is less than base_logging::INFO, returns base_logging::INFO.
799// If "s" is greater than base_logging::FATAL, returns
800// base_logging::ERROR. Otherwise, returns "s".
801LogSeverity NormalizeSeverity(LogSeverity s);
802
803} // namespace internal
804
805// A helper class for formatting "expr (V1 vs. V2)" in a CHECK_XX
806// statement. See MakeCheckOpString for sample usage. Other
807// approaches were considered: use of a template method (e.g.,
808// base::BuildCheckOpString(exprtext, base::Print<T1>, &v1,
809// base::Print<T2>, &v2), however this approach has complications
810// related to volatile arguments and function-pointer arguments).
James Kuszmaulba0ac1a2022-08-12 16:29:30 -0700811class GLOG_EXPORT CheckOpMessageBuilder {
Austin Schuh906616c2019-01-21 20:25:11 -0800812 public:
813 // Inserts "exprtext" and " (" to the stream.
814 explicit CheckOpMessageBuilder(const char *exprtext);
815 // Deletes "stream_".
816 ~CheckOpMessageBuilder();
817 // For inserting the first variable.
818 std::ostream* ForVar1() { return stream_; }
819 // For inserting the second variable (adds an intermediate " vs. ").
820 std::ostream* ForVar2();
821 // Get the result (inserts the closing ")").
822 std::string* NewString();
823
824 private:
825 std::ostringstream *stream_;
826};
827
828} // namespace base
829
830template <typename T1, typename T2>
831std::string* MakeCheckOpString(const T1& v1, const T2& v2, const char* exprtext) {
832 base::CheckOpMessageBuilder comb(exprtext);
833 MakeCheckOpValueString(comb.ForVar1(), v1);
834 MakeCheckOpValueString(comb.ForVar2(), v2);
835 return comb.NewString();
836}
837
838// Helper functions for CHECK_OP macro.
839// The (int, int) specialization works around the issue that the compiler
840// will not instantiate the template version of the function on values of
841// unnamed enum type - see comment below.
842#define DEFINE_CHECK_OP_IMPL(name, op) \
843 template <typename T1, typename T2> \
844 inline std::string* name##Impl(const T1& v1, const T2& v2, \
845 const char* exprtext) { \
846 if (GOOGLE_PREDICT_TRUE(v1 op v2)) return NULL; \
847 else return MakeCheckOpString(v1, v2, exprtext); \
848 } \
849 inline std::string* name##Impl(int v1, int v2, const char* exprtext) { \
850 return name##Impl<int, int>(v1, v2, exprtext); \
851 }
852
853// We use the full name Check_EQ, Check_NE, etc. in case the file including
854// base/logging.h provides its own #defines for the simpler names EQ, NE, etc.
855// This happens if, for example, those are used as token names in a
856// yacc grammar.
857DEFINE_CHECK_OP_IMPL(Check_EQ, ==) // Compilation error with CHECK_EQ(NULL, x)?
858DEFINE_CHECK_OP_IMPL(Check_NE, !=) // Use CHECK(x == NULL) instead.
859DEFINE_CHECK_OP_IMPL(Check_LE, <=)
860DEFINE_CHECK_OP_IMPL(Check_LT, < )
861DEFINE_CHECK_OP_IMPL(Check_GE, >=)
862DEFINE_CHECK_OP_IMPL(Check_GT, > )
863#undef DEFINE_CHECK_OP_IMPL
864
865// Helper macro for binary operators.
866// Don't use this macro directly in your code, use CHECK_EQ et al below.
867
868#if defined(STATIC_ANALYSIS)
869// Only for static analysis tool to know that it is equivalent to assert
870#define CHECK_OP_LOG(name, op, val1, val2, log) CHECK((val1) op (val2))
871#elif DCHECK_IS_ON()
872// In debug mode, avoid constructing CheckOpStrings if possible,
873// to reduce the overhead of CHECK statments by 2x.
874// Real DCHECK-heavy tests have seen 1.5x speedups.
875
876// The meaning of "string" might be different between now and
877// when this macro gets invoked (e.g., if someone is experimenting
878// with other string implementations that get defined after this
879// file is included). Save the current meaning now and use it
880// in the macro.
881typedef std::string _Check_string;
882#define CHECK_OP_LOG(name, op, val1, val2, log) \
883 while (@ac_google_namespace@::_Check_string* _result = \
884 @ac_google_namespace@::Check##name##Impl( \
885 @ac_google_namespace@::GetReferenceableValue(val1), \
886 @ac_google_namespace@::GetReferenceableValue(val2), \
887 #val1 " " #op " " #val2)) \
888 log(__FILE__, __LINE__, \
889 @ac_google_namespace@::CheckOpString(_result)).stream()
890#else
891// In optimized mode, use CheckOpString to hint to compiler that
892// the while condition is unlikely.
893#define CHECK_OP_LOG(name, op, val1, val2, log) \
894 while (@ac_google_namespace@::CheckOpString _result = \
895 @ac_google_namespace@::Check##name##Impl( \
896 @ac_google_namespace@::GetReferenceableValue(val1), \
897 @ac_google_namespace@::GetReferenceableValue(val2), \
898 #val1 " " #op " " #val2)) \
899 log(__FILE__, __LINE__, _result).stream()
900#endif // STATIC_ANALYSIS, DCHECK_IS_ON()
901
902#if GOOGLE_STRIP_LOG <= 3
903#define CHECK_OP(name, op, val1, val2) \
904 CHECK_OP_LOG(name, op, val1, val2, @ac_google_namespace@::LogMessageFatal)
905#else
906#define CHECK_OP(name, op, val1, val2) \
907 CHECK_OP_LOG(name, op, val1, val2, @ac_google_namespace@::NullStreamFatal)
908#endif // STRIP_LOG <= 3
909
910// Equality/Inequality checks - compare two values, and log a FATAL message
911// including the two values when the result is not as expected. The values
912// must have operator<<(ostream, ...) defined.
913//
914// You may append to the error message like so:
915// CHECK_NE(1, 2) << ": The world must be ending!";
916//
917// We are very careful to ensure that each argument is evaluated exactly
918// once, and that anything which is legal to pass as a function argument is
919// legal here. In particular, the arguments may be temporary expressions
920// which will end up being destroyed at the end of the apparent statement,
921// for example:
922// CHECK_EQ(string("abc")[1], 'b');
923//
924// WARNING: These don't compile correctly if one of the arguments is a pointer
925// and the other is NULL. To work around this, simply static_cast NULL to the
926// type of the desired pointer.
927
928#define CHECK_EQ(val1, val2) CHECK_OP(_EQ, ==, val1, val2)
929#define CHECK_NE(val1, val2) CHECK_OP(_NE, !=, val1, val2)
930#define CHECK_LE(val1, val2) CHECK_OP(_LE, <=, val1, val2)
931#define CHECK_LT(val1, val2) CHECK_OP(_LT, < , val1, val2)
932#define CHECK_GE(val1, val2) CHECK_OP(_GE, >=, val1, val2)
933#define CHECK_GT(val1, val2) CHECK_OP(_GT, > , val1, val2)
934
935// Check that the input is non NULL. This very useful in constructor
936// initializer lists.
937
938#define CHECK_NOTNULL(val) \
939 @ac_google_namespace@::CheckNotNull(__FILE__, __LINE__, "'" #val "' Must be non NULL", (val))
940
941// Helper functions for string comparisons.
942// To avoid bloat, the definitions are in logging.cc.
943#define DECLARE_CHECK_STROP_IMPL(func, expected) \
James Kuszmaulba0ac1a2022-08-12 16:29:30 -0700944 GLOG_EXPORT std::string* Check##func##expected##Impl( \
Austin Schuh906616c2019-01-21 20:25:11 -0800945 const char* s1, const char* s2, const char* names);
946DECLARE_CHECK_STROP_IMPL(strcmp, true)
947DECLARE_CHECK_STROP_IMPL(strcmp, false)
948DECLARE_CHECK_STROP_IMPL(strcasecmp, true)
949DECLARE_CHECK_STROP_IMPL(strcasecmp, false)
950#undef DECLARE_CHECK_STROP_IMPL
951
952// Helper macro for string comparisons.
953// Don't use this macro directly in your code, use CHECK_STREQ et al below.
954#define CHECK_STROP(func, op, expected, s1, s2) \
955 while (@ac_google_namespace@::CheckOpString _result = \
956 @ac_google_namespace@::Check##func##expected##Impl((s1), (s2), \
957 #s1 " " #op " " #s2)) \
958 LOG(FATAL) << *_result.str_
959
960
961// String (char*) equality/inequality checks.
962// CASE versions are case-insensitive.
963//
964// Note that "s1" and "s2" may be temporary strings which are destroyed
965// by the compiler at the end of the current "full expression"
966// (e.g. CHECK_STREQ(Foo().c_str(), Bar().c_str())).
967
968#define CHECK_STREQ(s1, s2) CHECK_STROP(strcmp, ==, true, s1, s2)
969#define CHECK_STRNE(s1, s2) CHECK_STROP(strcmp, !=, false, s1, s2)
970#define CHECK_STRCASEEQ(s1, s2) CHECK_STROP(strcasecmp, ==, true, s1, s2)
971#define CHECK_STRCASENE(s1, s2) CHECK_STROP(strcasecmp, !=, false, s1, s2)
972
973#define CHECK_INDEX(I,A) CHECK(I < (sizeof(A)/sizeof(A[0])))
974#define CHECK_BOUND(B,A) CHECK(B <= (sizeof(A)/sizeof(A[0])))
975
976#define CHECK_DOUBLE_EQ(val1, val2) \
977 do { \
978 CHECK_LE((val1), (val2)+0.000000000000001L); \
979 CHECK_GE((val1), (val2)-0.000000000000001L); \
980 } while (0)
981
982#define CHECK_NEAR(val1, val2, margin) \
983 do { \
984 CHECK_LE((val1), (val2)+(margin)); \
985 CHECK_GE((val1), (val2)-(margin)); \
986 } while (0)
987
988// perror()..googly style!
989//
990// PLOG() and PLOG_IF() and PCHECK() behave exactly like their LOG* and
991// CHECK equivalents with the addition that they postpend a description
992// of the current state of errno to their output lines.
993
994#define PLOG(severity) GOOGLE_PLOG(severity, 0).stream()
995
996#define GOOGLE_PLOG(severity, counter) \
997 @ac_google_namespace@::ErrnoLogMessage( \
998 __FILE__, __LINE__, @ac_google_namespace@::GLOG_ ## severity, counter, \
999 &@ac_google_namespace@::LogMessage::SendToLog)
1000
James Kuszmaulba0ac1a2022-08-12 16:29:30 -07001001#define PLOG_IF(severity, condition) if(condition) PLOG(severity)
Austin Schuh906616c2019-01-21 20:25:11 -08001002
1003// A CHECK() macro that postpends errno if the condition is false. E.g.
1004//
1005// if (poll(fds, nfds, timeout) == -1) { PCHECK(errno == EINTR); ... }
1006#define PCHECK(condition) \
1007 PLOG_IF(FATAL, GOOGLE_PREDICT_BRANCH_NOT_TAKEN(!(condition))) \
1008 << "Check failed: " #condition " "
1009
1010// A CHECK() macro that lets you assert the success of a function that
1011// returns -1 and sets errno in case of an error. E.g.
1012//
1013// CHECK_ERR(mkdir(path, 0700));
1014//
1015// or
1016//
1017// int fd = open(filename, flags); CHECK_ERR(fd) << ": open " << filename;
1018#define CHECK_ERR(invocation) \
1019PLOG_IF(FATAL, GOOGLE_PREDICT_BRANCH_NOT_TAKEN((invocation) == -1)) \
1020 << #invocation
1021
1022// Use macro expansion to create, for each use of LOG_EVERY_N(), static
1023// variables with the __LINE__ expansion as part of the variable name.
1024#define LOG_EVERY_N_VARNAME(base, line) LOG_EVERY_N_VARNAME_CONCAT(base, line)
1025#define LOG_EVERY_N_VARNAME_CONCAT(base, line) base ## line
1026
1027#define LOG_OCCURRENCES LOG_EVERY_N_VARNAME(occurrences_, __LINE__)
1028#define LOG_OCCURRENCES_MOD_N LOG_EVERY_N_VARNAME(occurrences_mod_n_, __LINE__)
1029
James Kuszmaulba0ac1a2022-08-12 16:29:30 -07001030#if @ac_cv_cxx11_constexpr@ && __cplusplus >= 201103L
1031#define GLOG_CONSTEXPR constexpr
1032#else
1033#define GLOG_CONSTEXPR const
1034#endif
1035
1036#define LOG_TIME_PERIOD LOG_EVERY_N_VARNAME(timePeriod_, __LINE__)
1037#define LOG_PREVIOUS_TIME_RAW LOG_EVERY_N_VARNAME(previousTimeRaw_, __LINE__)
1038#define LOG_TIME_DELTA LOG_EVERY_N_VARNAME(deltaTime_, __LINE__)
1039#define LOG_CURRENT_TIME LOG_EVERY_N_VARNAME(currentTime_, __LINE__)
1040#define LOG_PREVIOUS_TIME LOG_EVERY_N_VARNAME(previousTime_, __LINE__)
1041
1042#if defined(__has_feature)
1043# if __has_feature(thread_sanitizer)
1044# define GLOG_SANITIZE_THREAD 1
1045# endif
1046#endif
1047
1048#if !defined(GLOG_SANITIZE_THREAD) && defined(__SANITIZE_THREAD__) && __SANITIZE_THREAD__
1049# define GLOG_SANITIZE_THREAD 1
1050#endif
1051
1052#if defined(GLOG_SANITIZE_THREAD)
1053#define GLOG_IFDEF_THREAD_SANITIZER(X) X
1054#else
1055#define GLOG_IFDEF_THREAD_SANITIZER(X)
1056#endif
1057
1058#if defined(GLOG_SANITIZE_THREAD)
1059} // namespace google
1060
1061// We need to identify the static variables as "benign" races
1062// to avoid noisy reports from TSAN.
1063extern "C" void AnnotateBenignRaceSized(
1064 const char *file,
1065 int line,
1066 const volatile void *mem,
1067 size_t size,
1068 const char *description);
1069
1070namespace google {
1071#endif
1072
1073#if __cplusplus >= 201103L && @ac_cv_cxx11_chrono@ && @ac_cv_cxx11_atomic@ // Have <chrono> and <atomic>
1074#define SOME_KIND_OF_LOG_EVERY_T(severity, seconds) \
1075 GLOG_CONSTEXPR std::chrono::nanoseconds LOG_TIME_PERIOD = std::chrono::duration_cast<std::chrono::nanoseconds>(std::chrono::duration<double>(seconds)); \
1076 static std::atomic<@ac_google_namespace@::int64> LOG_PREVIOUS_TIME_RAW; \
1077 GLOG_IFDEF_THREAD_SANITIZER( \
1078 AnnotateBenignRaceSized(__FILE__, __LINE__, &LOG_TIME_PERIOD, sizeof(@ac_google_namespace@::int64), "")); \
1079 GLOG_IFDEF_THREAD_SANITIZER( \
1080 AnnotateBenignRaceSized(__FILE__, __LINE__, &LOG_PREVIOUS_TIME_RAW, sizeof(@ac_google_namespace@::int64), "")); \
1081 const auto LOG_CURRENT_TIME = std::chrono::duration_cast<std::chrono::nanoseconds>(std::chrono::steady_clock::now().time_since_epoch()); \
1082 const auto LOG_PREVIOUS_TIME = LOG_PREVIOUS_TIME_RAW.load(std::memory_order_relaxed); \
1083 const auto LOG_TIME_DELTA = LOG_CURRENT_TIME - std::chrono::nanoseconds(LOG_PREVIOUS_TIME); \
1084 if (LOG_TIME_DELTA > LOG_TIME_PERIOD) \
1085 LOG_PREVIOUS_TIME_RAW.store(std::chrono::duration_cast<std::chrono::nanoseconds>(LOG_CURRENT_TIME).count(), std::memory_order_relaxed); \
1086 if (LOG_TIME_DELTA > LOG_TIME_PERIOD) @ac_google_namespace@::LogMessage( \
1087 __FILE__, __LINE__, @ac_google_namespace@::GLOG_ ## severity).stream()
1088#elif defined(GLOG_OS_WINDOWS)
1089#define SOME_KIND_OF_LOG_EVERY_T(severity, seconds) \
1090 GLOG_CONSTEXPR LONGLONG LOG_TIME_PERIOD = (seconds) * LONGLONG(1000000000); \
1091 static LARGE_INTEGER LOG_PREVIOUS_TIME; \
1092 LONGLONG LOG_TIME_DELTA; \
1093 { \
1094 LARGE_INTEGER currTime; \
1095 LARGE_INTEGER freq; \
1096 QueryPerformanceCounter(&currTime); \
1097 QueryPerformanceFrequency(&freq); \
1098 InterlockedCompareExchange64(&LOG_PREVIOUS_TIME.QuadPart, currTime.QuadPart, 0); \
1099 LOG_TIME_DELTA = (currTime.QuadPart - LOG_PREVIOUS_TIME.QuadPart) * LONGLONG(1000000000) / freq.QuadPart; \
1100 if (LOG_TIME_DELTA > LOG_TIME_PERIOD) InterlockedExchange64(&LOG_PREVIOUS_TIME.QuadPart, currTime.QuadPart); \
1101 } \
1102 if (LOG_TIME_DELTA > LOG_TIME_PERIOD) \
1103 @ac_google_namespace@::LogMessage( \
1104 __FILE__, __LINE__, @ac_google_namespace@::GLOG_ ## severity).stream()
1105#else
1106#define SOME_KIND_OF_LOG_EVERY_T(severity, seconds) \
1107 GLOG_CONSTEXPR @ac_google_namespace@::int64 LOG_TIME_PERIOD(seconds * 1000000000); \
1108 static @ac_google_namespace@::int64 LOG_PREVIOUS_TIME; \
1109 @ac_google_namespace@::int64 LOG_TIME_DELTA = 0; \
1110 { \
1111 timespec currentTime = {}; \
1112 clock_gettime(CLOCK_MONOTONIC, &currentTime); \
1113 LOG_TIME_DELTA = (currentTime.tv_sec * 1000000000 + currentTime.tv_nsec) - LOG_PREVIOUS_TIME; \
1114 } \
1115 if (LOG_TIME_DELTA > LOG_TIME_PERIOD) __sync_add_and_fetch(&LOG_PREVIOUS_TIME, LOG_TIME_DELTA); \
1116 if (LOG_TIME_DELTA > LOG_TIME_PERIOD) @ac_google_namespace@::LogMessage( \
1117 __FILE__, __LINE__, @ac_google_namespace@::GLOG_ ## severity).stream()
1118#endif
1119
1120#if @ac_cv_cxx11_atomic@ && __cplusplus >= 201103L
Austin Schuh906616c2019-01-21 20:25:11 -08001121#define SOME_KIND_OF_LOG_EVERY_N(severity, n, what_to_do) \
James Kuszmaulba0ac1a2022-08-12 16:29:30 -07001122 static std::atomic<int> LOG_OCCURRENCES(0), LOG_OCCURRENCES_MOD_N(0); \
1123 GLOG_IFDEF_THREAD_SANITIZER(AnnotateBenignRaceSized(__FILE__, __LINE__, &LOG_OCCURRENCES, sizeof(int), "")); \
1124 GLOG_IFDEF_THREAD_SANITIZER(AnnotateBenignRaceSized(__FILE__, __LINE__, &LOG_OCCURRENCES_MOD_N, sizeof(int), "")); \
Austin Schuh906616c2019-01-21 20:25:11 -08001125 ++LOG_OCCURRENCES; \
1126 if (++LOG_OCCURRENCES_MOD_N > n) LOG_OCCURRENCES_MOD_N -= n; \
1127 if (LOG_OCCURRENCES_MOD_N == 1) \
1128 @ac_google_namespace@::LogMessage( \
1129 __FILE__, __LINE__, @ac_google_namespace@::GLOG_ ## severity, LOG_OCCURRENCES, \
1130 &what_to_do).stream()
1131
1132#define SOME_KIND_OF_LOG_IF_EVERY_N(severity, condition, n, what_to_do) \
James Kuszmaulba0ac1a2022-08-12 16:29:30 -07001133 static std::atomic<int> LOG_OCCURRENCES(0), LOG_OCCURRENCES_MOD_N(0); \
1134 GLOG_IFDEF_THREAD_SANITIZER(AnnotateBenignRaceSized(__FILE__, __LINE__, &LOG_OCCURRENCES, sizeof(int), "")); \
1135 GLOG_IFDEF_THREAD_SANITIZER(AnnotateBenignRaceSized(__FILE__, __LINE__, &LOG_OCCURRENCES_MOD_N, sizeof(int), "")); \
Austin Schuh906616c2019-01-21 20:25:11 -08001136 ++LOG_OCCURRENCES; \
James Kuszmaulba0ac1a2022-08-12 16:29:30 -07001137 if ((condition) && \
Austin Schuh906616c2019-01-21 20:25:11 -08001138 ((LOG_OCCURRENCES_MOD_N=(LOG_OCCURRENCES_MOD_N + 1) % n) == (1 % n))) \
1139 @ac_google_namespace@::LogMessage( \
1140 __FILE__, __LINE__, @ac_google_namespace@::GLOG_ ## severity, LOG_OCCURRENCES, \
1141 &what_to_do).stream()
1142
1143#define SOME_KIND_OF_PLOG_EVERY_N(severity, n, what_to_do) \
James Kuszmaulba0ac1a2022-08-12 16:29:30 -07001144 static std::atomic<int> LOG_OCCURRENCES(0), LOG_OCCURRENCES_MOD_N(0); \
1145 GLOG_IFDEF_THREAD_SANITIZER(AnnotateBenignRaceSized(__FILE__, __LINE__, &LOG_OCCURRENCES, sizeof(int), "")); \
1146 GLOG_IFDEF_THREAD_SANITIZER(AnnotateBenignRaceSized(__FILE__, __LINE__, &LOG_OCCURRENCES_MOD_N, sizeof(int), "")); \
Austin Schuh906616c2019-01-21 20:25:11 -08001147 ++LOG_OCCURRENCES; \
1148 if (++LOG_OCCURRENCES_MOD_N > n) LOG_OCCURRENCES_MOD_N -= n; \
1149 if (LOG_OCCURRENCES_MOD_N == 1) \
1150 @ac_google_namespace@::ErrnoLogMessage( \
1151 __FILE__, __LINE__, @ac_google_namespace@::GLOG_ ## severity, LOG_OCCURRENCES, \
1152 &what_to_do).stream()
1153
1154#define SOME_KIND_OF_LOG_FIRST_N(severity, n, what_to_do) \
James Kuszmaulba0ac1a2022-08-12 16:29:30 -07001155 static std::atomic<int> LOG_OCCURRENCES(0); \
1156 GLOG_IFDEF_THREAD_SANITIZER(AnnotateBenignRaceSized(__FILE__, __LINE__, &LOG_OCCURRENCES, sizeof(int), "")); \
Austin Schuh906616c2019-01-21 20:25:11 -08001157 if (LOG_OCCURRENCES <= n) \
1158 ++LOG_OCCURRENCES; \
1159 if (LOG_OCCURRENCES <= n) \
1160 @ac_google_namespace@::LogMessage( \
1161 __FILE__, __LINE__, @ac_google_namespace@::GLOG_ ## severity, LOG_OCCURRENCES, \
1162 &what_to_do).stream()
1163
James Kuszmaulba0ac1a2022-08-12 16:29:30 -07001164#elif defined(GLOG_OS_WINDOWS)
1165
1166#define SOME_KIND_OF_LOG_EVERY_N(severity, n, what_to_do) \
1167 static volatile unsigned LOG_OCCURRENCES = 0; \
1168 static volatile unsigned LOG_OCCURRENCES_MOD_N = 0; \
1169 InterlockedIncrement(&LOG_OCCURRENCES); \
1170 if (InterlockedIncrement(&LOG_OCCURRENCES_MOD_N) > n) \
1171 InterlockedExchangeSubtract(&LOG_OCCURRENCES_MOD_N, n); \
1172 if (LOG_OCCURRENCES_MOD_N == 1) \
1173 @ac_google_namespace@::LogMessage( \
1174 __FILE__, __LINE__, @ac_google_namespace@::GLOG_ ## severity, LOG_OCCURRENCES, \
1175 &what_to_do).stream()
1176
1177#define SOME_KIND_OF_LOG_IF_EVERY_N(severity, condition, n, what_to_do) \
1178 static volatile unsigned LOG_OCCURRENCES = 0; \
1179 static volatile unsigned LOG_OCCURRENCES_MOD_N = 0; \
1180 InterlockedIncrement(&LOG_OCCURRENCES); \
1181 if ((condition) && \
1182 ((InterlockedIncrement(&LOG_OCCURRENCES_MOD_N), \
1183 (LOG_OCCURRENCES_MOD_N > n && InterlockedExchangeSubtract(&LOG_OCCURRENCES_MOD_N, n))), \
1184 LOG_OCCURRENCES_MOD_N == 1)) \
1185 @ac_google_namespace@::LogMessage( \
1186 __FILE__, __LINE__, @ac_google_namespace@::GLOG_ ## severity, LOG_OCCURRENCES, \
1187 &what_to_do).stream()
1188
1189#define SOME_KIND_OF_PLOG_EVERY_N(severity, n, what_to_do) \
1190 static volatile unsigned LOG_OCCURRENCES = 0; \
1191 static volatile unsigned LOG_OCCURRENCES_MOD_N = 0; \
1192 InterlockedIncrement(&LOG_OCCURRENCES); \
1193 if (InterlockedIncrement(&LOG_OCCURRENCES_MOD_N) > n) \
1194 InterlockedExchangeSubtract(&LOG_OCCURRENCES_MOD_N, n); \
1195 if (LOG_OCCURRENCES_MOD_N == 1) \
1196 @ac_google_namespace@::ErrnoLogMessage( \
1197 __FILE__, __LINE__, @ac_google_namespace@::GLOG_ ## severity, LOG_OCCURRENCES, \
1198 &what_to_do).stream()
1199
1200#define SOME_KIND_OF_LOG_FIRST_N(severity, n, what_to_do) \
1201 static volatile unsigned LOG_OCCURRENCES = 0; \
1202 if (LOG_OCCURRENCES <= n) \
1203 InterlockedIncrement(&LOG_OCCURRENCES); \
1204 if (LOG_OCCURRENCES <= n) \
1205 @ac_google_namespace@::LogMessage( \
1206 __FILE__, __LINE__, @ac_google_namespace@::GLOG_ ## severity, LOG_OCCURRENCES, \
1207 &what_to_do).stream()
1208
1209#else
1210
1211#define SOME_KIND_OF_LOG_EVERY_N(severity, n, what_to_do) \
1212 static int LOG_OCCURRENCES = 0, LOG_OCCURRENCES_MOD_N = 0; \
1213 __sync_add_and_fetch(&LOG_OCCURRENCES, 1); \
1214 if (__sync_add_and_fetch(&LOG_OCCURRENCES_MOD_N, 1) > n) \
1215 __sync_sub_and_fetch(&LOG_OCCURRENCES_MOD_N, n); \
1216 if (LOG_OCCURRENCES_MOD_N == 1) \
1217 @ac_google_namespace@::LogMessage( \
1218 __FILE__, __LINE__, @ac_google_namespace@::GLOG_ ## severity, LOG_OCCURRENCES, \
1219 &what_to_do).stream()
1220
1221#define SOME_KIND_OF_LOG_IF_EVERY_N(severity, condition, n, what_to_do) \
1222 static int LOG_OCCURRENCES = 0, LOG_OCCURRENCES_MOD_N = 0; \
1223 __sync_add_and_fetch(&LOG_OCCURRENCES, 1); \
1224 if ((condition) && \
1225 (__sync_add_and_fetch(&LOG_OCCURRENCES_MOD_N, 1) || true) && \
1226 ((LOG_OCCURRENCES_MOD_N >= n && __sync_sub_and_fetch(&LOG_OCCURRENCES_MOD_N, n)) || true) && \
1227 LOG_OCCURRENCES_MOD_N == (1 % n)) \
1228 @ac_google_namespace@::LogMessage( \
1229 __FILE__, __LINE__, @ac_google_namespace@::GLOG_ ## severity, LOG_OCCURRENCES, \
1230 &what_to_do).stream()
1231
1232#define SOME_KIND_OF_PLOG_EVERY_N(severity, n, what_to_do) \
1233 static int LOG_OCCURRENCES = 0, LOG_OCCURRENCES_MOD_N = 0; \
1234 __sync_add_and_fetch(&LOG_OCCURRENCES, 1); \
1235 if (__sync_add_and_fetch(&LOG_OCCURRENCES_MOD_N, 1) > n) \
1236 __sync_sub_and_fetch(&LOG_OCCURRENCES_MOD_N, n); \
1237 if (LOG_OCCURRENCES_MOD_N == 1) \
1238 @ac_google_namespace@::ErrnoLogMessage( \
1239 __FILE__, __LINE__, @ac_google_namespace@::GLOG_ ## severity, LOG_OCCURRENCES, \
1240 &what_to_do).stream()
1241
1242#define SOME_KIND_OF_LOG_FIRST_N(severity, n, what_to_do) \
1243 static int LOG_OCCURRENCES = 0; \
1244 if (LOG_OCCURRENCES <= n) \
1245 __sync_add_and_fetch(&LOG_OCCURRENCES, 1); \
1246 if (LOG_OCCURRENCES <= n) \
1247 @ac_google_namespace@::LogMessage( \
1248 __FILE__, __LINE__, @ac_google_namespace@::GLOG_ ## severity, LOG_OCCURRENCES, \
1249 &what_to_do).stream()
1250#endif
1251
Austin Schuh906616c2019-01-21 20:25:11 -08001252namespace glog_internal_namespace_ {
1253template <bool>
1254struct CompileAssert {
1255};
1256struct CrashReason;
1257
1258// Returns true if FailureSignalHandler is installed.
1259// Needs to be exported since it's used by the signalhandler_unittest.
James Kuszmaulba0ac1a2022-08-12 16:29:30 -07001260GLOG_EXPORT bool IsFailureSignalHandlerInstalled();
Austin Schuh906616c2019-01-21 20:25:11 -08001261} // namespace glog_internal_namespace_
1262
1263#define LOG_EVERY_N(severity, n) \
1264 SOME_KIND_OF_LOG_EVERY_N(severity, (n), @ac_google_namespace@::LogMessage::SendToLog)
1265
James Kuszmaulba0ac1a2022-08-12 16:29:30 -07001266#define LOG_EVERY_T(severity, T) SOME_KIND_OF_LOG_EVERY_T(severity, (T))
1267
Austin Schuh906616c2019-01-21 20:25:11 -08001268#define SYSLOG_EVERY_N(severity, n) \
1269 SOME_KIND_OF_LOG_EVERY_N(severity, (n), @ac_google_namespace@::LogMessage::SendToSyslogAndLog)
1270
1271#define PLOG_EVERY_N(severity, n) \
1272 SOME_KIND_OF_PLOG_EVERY_N(severity, (n), @ac_google_namespace@::LogMessage::SendToLog)
1273
1274#define LOG_FIRST_N(severity, n) \
1275 SOME_KIND_OF_LOG_FIRST_N(severity, (n), @ac_google_namespace@::LogMessage::SendToLog)
1276
1277#define LOG_IF_EVERY_N(severity, condition, n) \
1278 SOME_KIND_OF_LOG_IF_EVERY_N(severity, (condition), (n), @ac_google_namespace@::LogMessage::SendToLog)
1279
1280// We want the special COUNTER value available for LOG_EVERY_X()'ed messages
1281enum PRIVATE_Counter {COUNTER};
1282
1283#ifdef GLOG_NO_ABBREVIATED_SEVERITIES
1284// wingdi.h defines ERROR to be 0. When we call LOG(ERROR), it gets
1285// substituted with 0, and it expands to COMPACT_GOOGLE_LOG_0. To allow us
1286// to keep using this syntax, we define this macro to do the same thing
1287// as COMPACT_GOOGLE_LOG_ERROR.
1288#define COMPACT_GOOGLE_LOG_0 COMPACT_GOOGLE_LOG_ERROR
1289#define SYSLOG_0 SYSLOG_ERROR
1290#define LOG_TO_STRING_0 LOG_TO_STRING_ERROR
1291// Needed for LOG_IS_ON(ERROR).
1292const LogSeverity GLOG_0 = GLOG_ERROR;
1293#else
1294// Users may include windows.h after logging.h without
1295// GLOG_NO_ABBREVIATED_SEVERITIES nor WIN32_LEAN_AND_MEAN.
1296// For this case, we cannot detect if ERROR is defined before users
1297// actually use ERROR. Let's make an undefined symbol to warn users.
1298# define GLOG_ERROR_MSG ERROR_macro_is_defined_Define_GLOG_NO_ABBREVIATED_SEVERITIES_before_including_logging_h_See_the_document_for_detail
1299# define COMPACT_GOOGLE_LOG_0 GLOG_ERROR_MSG
1300# define SYSLOG_0 GLOG_ERROR_MSG
1301# define LOG_TO_STRING_0 GLOG_ERROR_MSG
1302# define GLOG_0 GLOG_ERROR_MSG
1303#endif
1304
1305// Plus some debug-logging macros that get compiled to nothing for production
1306
1307#if DCHECK_IS_ON()
1308
1309#define DLOG(severity) LOG(severity)
1310#define DVLOG(verboselevel) VLOG(verboselevel)
1311#define DLOG_IF(severity, condition) LOG_IF(severity, condition)
1312#define DLOG_EVERY_N(severity, n) LOG_EVERY_N(severity, n)
1313#define DLOG_IF_EVERY_N(severity, condition, n) \
1314 LOG_IF_EVERY_N(severity, condition, n)
1315#define DLOG_ASSERT(condition) LOG_ASSERT(condition)
1316
1317// debug-only checking. executed if DCHECK_IS_ON().
1318#define DCHECK(condition) CHECK(condition)
1319#define DCHECK_EQ(val1, val2) CHECK_EQ(val1, val2)
1320#define DCHECK_NE(val1, val2) CHECK_NE(val1, val2)
1321#define DCHECK_LE(val1, val2) CHECK_LE(val1, val2)
1322#define DCHECK_LT(val1, val2) CHECK_LT(val1, val2)
1323#define DCHECK_GE(val1, val2) CHECK_GE(val1, val2)
1324#define DCHECK_GT(val1, val2) CHECK_GT(val1, val2)
1325#define DCHECK_NOTNULL(val) CHECK_NOTNULL(val)
1326#define DCHECK_STREQ(str1, str2) CHECK_STREQ(str1, str2)
1327#define DCHECK_STRCASEEQ(str1, str2) CHECK_STRCASEEQ(str1, str2)
1328#define DCHECK_STRNE(str1, str2) CHECK_STRNE(str1, str2)
1329#define DCHECK_STRCASENE(str1, str2) CHECK_STRCASENE(str1, str2)
1330
1331#else // !DCHECK_IS_ON()
1332
James Kuszmaulba0ac1a2022-08-12 16:29:30 -07001333#define DLOG(severity) if((false)) LOG(severity)
Austin Schuh906616c2019-01-21 20:25:11 -08001334
James Kuszmaulba0ac1a2022-08-12 16:29:30 -07001335#define DVLOG(verboselevel) if((false) && VLOG_IS_ON(verboselevel)) LOG(INFO)
Austin Schuh906616c2019-01-21 20:25:11 -08001336
James Kuszmaulba0ac1a2022-08-12 16:29:30 -07001337#define DLOG_IF(severity, condition) if((false) && (condition)) LOG(severity)
Austin Schuh906616c2019-01-21 20:25:11 -08001338
James Kuszmaulba0ac1a2022-08-12 16:29:30 -07001339#define DLOG_EVERY_N(severity, n) if((false)) LOG(severity)
Austin Schuh906616c2019-01-21 20:25:11 -08001340
James Kuszmaulba0ac1a2022-08-12 16:29:30 -07001341#define DLOG_IF_EVERY_N(severity, condition, n) if((false) && (condition)) LOG(severity)
Austin Schuh906616c2019-01-21 20:25:11 -08001342
James Kuszmaulba0ac1a2022-08-12 16:29:30 -07001343#define DLOG_ASSERT(condition) if((false)) LOG_ASSERT(condition)
Austin Schuh906616c2019-01-21 20:25:11 -08001344
1345// MSVC warning C4127: conditional expression is constant
1346#define DCHECK(condition) \
1347 GLOG_MSVC_PUSH_DISABLE_WARNING(4127) \
1348 while (false) \
1349 GLOG_MSVC_POP_WARNING() CHECK(condition)
1350
1351#define DCHECK_EQ(val1, val2) \
1352 GLOG_MSVC_PUSH_DISABLE_WARNING(4127) \
1353 while (false) \
1354 GLOG_MSVC_POP_WARNING() CHECK_EQ(val1, val2)
1355
1356#define DCHECK_NE(val1, val2) \
1357 GLOG_MSVC_PUSH_DISABLE_WARNING(4127) \
1358 while (false) \
1359 GLOG_MSVC_POP_WARNING() CHECK_NE(val1, val2)
1360
1361#define DCHECK_LE(val1, val2) \
1362 GLOG_MSVC_PUSH_DISABLE_WARNING(4127) \
1363 while (false) \
1364 GLOG_MSVC_POP_WARNING() CHECK_LE(val1, val2)
1365
1366#define DCHECK_LT(val1, val2) \
1367 GLOG_MSVC_PUSH_DISABLE_WARNING(4127) \
1368 while (false) \
1369 GLOG_MSVC_POP_WARNING() CHECK_LT(val1, val2)
1370
1371#define DCHECK_GE(val1, val2) \
1372 GLOG_MSVC_PUSH_DISABLE_WARNING(4127) \
1373 while (false) \
1374 GLOG_MSVC_POP_WARNING() CHECK_GE(val1, val2)
1375
1376#define DCHECK_GT(val1, val2) \
1377 GLOG_MSVC_PUSH_DISABLE_WARNING(4127) \
1378 while (false) \
1379 GLOG_MSVC_POP_WARNING() CHECK_GT(val1, val2)
1380
1381// You may see warnings in release mode if you don't use the return
1382// value of DCHECK_NOTNULL. Please just use DCHECK for such cases.
1383#define DCHECK_NOTNULL(val) (val)
1384
1385#define DCHECK_STREQ(str1, str2) \
1386 GLOG_MSVC_PUSH_DISABLE_WARNING(4127) \
1387 while (false) \
1388 GLOG_MSVC_POP_WARNING() CHECK_STREQ(str1, str2)
1389
1390#define DCHECK_STRCASEEQ(str1, str2) \
1391 GLOG_MSVC_PUSH_DISABLE_WARNING(4127) \
1392 while (false) \
1393 GLOG_MSVC_POP_WARNING() CHECK_STRCASEEQ(str1, str2)
1394
1395#define DCHECK_STRNE(str1, str2) \
1396 GLOG_MSVC_PUSH_DISABLE_WARNING(4127) \
1397 while (false) \
1398 GLOG_MSVC_POP_WARNING() CHECK_STRNE(str1, str2)
1399
1400#define DCHECK_STRCASENE(str1, str2) \
1401 GLOG_MSVC_PUSH_DISABLE_WARNING(4127) \
1402 while (false) \
1403 GLOG_MSVC_POP_WARNING() CHECK_STRCASENE(str1, str2)
1404
1405#endif // DCHECK_IS_ON()
1406
1407// Log only in verbose mode.
1408
1409#define VLOG(verboselevel) LOG_IF(INFO, VLOG_IS_ON(verboselevel))
1410
1411#define VLOG_IF(verboselevel, condition) \
1412 LOG_IF(INFO, (condition) && VLOG_IS_ON(verboselevel))
1413
1414#define VLOG_EVERY_N(verboselevel, n) \
1415 LOG_IF_EVERY_N(INFO, VLOG_IS_ON(verboselevel), n)
1416
1417#define VLOG_IF_EVERY_N(verboselevel, condition, n) \
1418 LOG_IF_EVERY_N(INFO, (condition) && VLOG_IS_ON(verboselevel), n)
1419
1420namespace base_logging {
1421
1422// LogMessage::LogStream is a std::ostream backed by this streambuf.
1423// This class ignores overflow and leaves two bytes at the end of the
1424// buffer to allow for a '\n' and '\0'.
James Kuszmaulba0ac1a2022-08-12 16:29:30 -07001425class GLOG_EXPORT LogStreamBuf : public std::streambuf {
Austin Schuh906616c2019-01-21 20:25:11 -08001426 public:
1427 // REQUIREMENTS: "len" must be >= 2 to account for the '\n' and '\0'.
1428 LogStreamBuf(char *buf, int len) {
1429 setp(buf, buf + len - 2);
1430 }
1431
1432 // This effectively ignores overflow.
James Kuszmaulba0ac1a2022-08-12 16:29:30 -07001433 int_type overflow(int_type ch) {
Austin Schuh906616c2019-01-21 20:25:11 -08001434 return ch;
1435 }
1436
1437 // Legacy public ostrstream method.
James Kuszmaulba0ac1a2022-08-12 16:29:30 -07001438 size_t pcount() const { return static_cast<size_t>(pptr() - pbase()); }
Austin Schuh906616c2019-01-21 20:25:11 -08001439 char* pbase() const { return std::streambuf::pbase(); }
1440};
1441
1442} // namespace base_logging
1443
1444//
1445// This class more or less represents a particular log message. You
1446// create an instance of LogMessage and then stream stuff to it.
1447// When you finish streaming to it, ~LogMessage is called and the
1448// full message gets streamed to the appropriate destination.
1449//
1450// You shouldn't actually use LogMessage's constructor to log things,
1451// though. You should use the LOG() macro (and variants thereof)
1452// above.
James Kuszmaulba0ac1a2022-08-12 16:29:30 -07001453class GLOG_EXPORT LogMessage {
Austin Schuh906616c2019-01-21 20:25:11 -08001454public:
1455 enum {
1456 // Passing kNoLogPrefix for the line number disables the
1457 // log-message prefix. Useful for using the LogMessage
1458 // infrastructure as a printing utility. See also the --log_prefix
1459 // flag for controlling the log-message prefix on an
1460 // application-wide basis.
1461 kNoLogPrefix = -1
1462 };
1463
1464 // LogStream inherit from non-DLL-exported class (std::ostrstream)
1465 // and VC++ produces a warning for this situation.
1466 // However, MSDN says "C4275 can be ignored in Microsoft Visual C++
1467 // 2005 if you are deriving from a type in the Standard C++ Library"
1468 // http://msdn.microsoft.com/en-us/library/3tdb471s(VS.80).aspx
1469 // Let's just ignore the warning.
James Kuszmaulba0ac1a2022-08-12 16:29:30 -07001470GLOG_MSVC_PUSH_DISABLE_WARNING(4275)
1471 class GLOG_EXPORT LogStream : public std::ostream {
1472GLOG_MSVC_POP_WARNING()
Austin Schuh906616c2019-01-21 20:25:11 -08001473 public:
James Kuszmaulba0ac1a2022-08-12 16:29:30 -07001474 LogStream(char *buf, int len, int64 ctr)
Austin Schuh906616c2019-01-21 20:25:11 -08001475 : std::ostream(NULL),
1476 streambuf_(buf, len),
1477 ctr_(ctr),
1478 self_(this) {
1479 rdbuf(&streambuf_);
1480 }
1481
James Kuszmaulba0ac1a2022-08-12 16:29:30 -07001482 int64 ctr() const { return ctr_; }
1483 void set_ctr(int64 ctr) { ctr_ = ctr; }
Austin Schuh906616c2019-01-21 20:25:11 -08001484 LogStream* self() const { return self_; }
1485
1486 // Legacy std::streambuf methods.
1487 size_t pcount() const { return streambuf_.pcount(); }
1488 char* pbase() const { return streambuf_.pbase(); }
1489 char* str() const { return pbase(); }
1490
1491 private:
1492 LogStream(const LogStream&);
1493 LogStream& operator=(const LogStream&);
1494 base_logging::LogStreamBuf streambuf_;
James Kuszmaulba0ac1a2022-08-12 16:29:30 -07001495 int64 ctr_; // Counter hack (for the LOG_EVERY_X() macro)
Austin Schuh906616c2019-01-21 20:25:11 -08001496 LogStream *self_; // Consistency check hack
1497 };
1498
1499public:
1500 // icc 8 requires this typedef to avoid an internal compiler error.
1501 typedef void (LogMessage::*SendMethod)();
1502
James Kuszmaulba0ac1a2022-08-12 16:29:30 -07001503 LogMessage(const char* file, int line, LogSeverity severity, int64 ctr,
Austin Schuh906616c2019-01-21 20:25:11 -08001504 SendMethod send_method);
1505
1506 // Two special constructors that generate reduced amounts of code at
1507 // LOG call sites for common cases.
1508
1509 // Used for LOG(INFO): Implied are:
1510 // severity = INFO, ctr = 0, send_method = &LogMessage::SendToLog.
1511 //
1512 // Using this constructor instead of the more complex constructor above
1513 // saves 19 bytes per call site.
1514 LogMessage(const char* file, int line);
1515
1516 // Used for LOG(severity) where severity != INFO. Implied
1517 // are: ctr = 0, send_method = &LogMessage::SendToLog
1518 //
1519 // Using this constructor instead of the more complex constructor above
1520 // saves 17 bytes per call site.
1521 LogMessage(const char* file, int line, LogSeverity severity);
1522
1523 // Constructor to log this message to a specified sink (if not NULL).
1524 // Implied are: ctr = 0, send_method = &LogMessage::SendToSinkAndLog if
1525 // also_send_to_log is true, send_method = &LogMessage::SendToSink otherwise.
1526 LogMessage(const char* file, int line, LogSeverity severity, LogSink* sink,
1527 bool also_send_to_log);
1528
1529 // Constructor where we also give a vector<string> pointer
1530 // for storing the messages (if the pointer is not NULL).
1531 // Implied are: ctr = 0, send_method = &LogMessage::SaveOrSendToLog.
1532 LogMessage(const char* file, int line, LogSeverity severity,
1533 std::vector<std::string>* outvec);
1534
1535 // Constructor where we also give a string pointer for storing the
1536 // message (if the pointer is not NULL). Implied are: ctr = 0,
1537 // send_method = &LogMessage::WriteToStringAndLog.
1538 LogMessage(const char* file, int line, LogSeverity severity,
1539 std::string* message);
1540
1541 // A special constructor used for check failures
1542 LogMessage(const char* file, int line, const CheckOpString& result);
1543
1544 ~LogMessage();
1545
1546 // Flush a buffered message to the sink set in the constructor. Always
1547 // called by the destructor, it may also be called from elsewhere if
1548 // needed. Only the first call is actioned; any later ones are ignored.
1549 void Flush();
1550
1551 // An arbitrary limit on the length of a single log message. This
1552 // is so that streaming can be done more efficiently.
1553 static const size_t kMaxLogMessageLen;
1554
1555 // Theses should not be called directly outside of logging.*,
1556 // only passed as SendMethod arguments to other LogMessage methods:
1557 void SendToLog(); // Actually dispatch to the logs
1558 void SendToSyslogAndLog(); // Actually dispatch to syslog and the logs
1559
1560 // Call abort() or similar to perform LOG(FATAL) crash.
1561 static void @ac_cv___attribute___noreturn@ Fail();
1562
1563 std::ostream& stream();
1564
1565 int preserved_errno() const;
1566
1567 // Must be called without the log_mutex held. (L < log_mutex)
1568 static int64 num_messages(int severity);
1569
James Kuszmaulba0ac1a2022-08-12 16:29:30 -07001570 const LogMessageTime& getLogMessageTime() const;
1571
Austin Schuh906616c2019-01-21 20:25:11 -08001572 struct LogMessageData;
1573
1574private:
1575 // Fully internal SendMethod cases:
1576 void SendToSinkAndLog(); // Send to sink if provided and dispatch to the logs
1577 void SendToSink(); // Send to sink if provided, do nothing otherwise.
1578
1579 // Write to string if provided and dispatch to the logs.
1580 void WriteToStringAndLog();
1581
1582 void SaveOrSendToLog(); // Save to stringvec if provided, else to logs
1583
1584 void Init(const char* file, int line, LogSeverity severity,
1585 void (LogMessage::*send_method)());
1586
1587 // Used to fill in crash information during LOG(FATAL) failures.
1588 void RecordCrashReason(glog_internal_namespace_::CrashReason* reason);
1589
1590 // Counts of messages sent at each priority:
1591 static int64 num_messages_[NUM_SEVERITIES]; // under log_mutex
1592
1593 // We keep the data in a separate struct so that each instance of
1594 // LogMessage uses less stack space.
1595 LogMessageData* allocated_;
1596 LogMessageData* data_;
James Kuszmaulba0ac1a2022-08-12 16:29:30 -07001597 LogMessageTime logmsgtime_;
Austin Schuh906616c2019-01-21 20:25:11 -08001598
1599 friend class LogDestination;
1600
1601 LogMessage(const LogMessage&);
1602 void operator=(const LogMessage&);
1603};
1604
1605// This class happens to be thread-hostile because all instances share
1606// a single data buffer, but since it can only be created just before
1607// the process dies, we don't worry so much.
James Kuszmaulba0ac1a2022-08-12 16:29:30 -07001608class GLOG_EXPORT LogMessageFatal : public LogMessage {
Austin Schuh906616c2019-01-21 20:25:11 -08001609 public:
1610 LogMessageFatal(const char* file, int line);
1611 LogMessageFatal(const char* file, int line, const CheckOpString& result);
1612 @ac_cv___attribute___noreturn@ ~LogMessageFatal();
1613};
1614
1615// A non-macro interface to the log facility; (useful
1616// when the logging level is not a compile-time constant).
1617inline void LogAtLevel(int const severity, std::string const &msg) {
1618 LogMessage(__FILE__, __LINE__, severity).stream() << msg;
1619}
1620
1621// A macro alternative of LogAtLevel. New code may want to use this
1622// version since there are two advantages: 1. this version outputs the
1623// file name and the line number where this macro is put like other
1624// LOG macros, 2. this macro can be used as C++ stream.
1625#define LOG_AT_LEVEL(severity) @ac_google_namespace@::LogMessage(__FILE__, __LINE__, severity).stream()
1626
1627// Check if it's compiled in C++11 mode.
1628//
1629// GXX_EXPERIMENTAL_CXX0X is defined by gcc and clang up to at least
1630// gcc-4.7 and clang-3.1 (2011-12-13). __cplusplus was defined to 1
1631// in gcc before 4.7 (Crosstool 16) and clang before 3.1, but is
1632// defined according to the language version in effect thereafter.
1633// Microsoft Visual Studio 14 (2015) sets __cplusplus==199711 despite
1634// reasonably good C++11 support, so we set LANG_CXX for it and
1635// newer versions (_MSC_VER >= 1900).
1636#if (defined(__GXX_EXPERIMENTAL_CXX0X__) || __cplusplus >= 201103L || \
James Kuszmaulba0ac1a2022-08-12 16:29:30 -07001637 (defined(_MSC_VER) && _MSC_VER >= 1900)) && !defined(__UCLIBCXX_MAJOR__)
Austin Schuh906616c2019-01-21 20:25:11 -08001638// Helper for CHECK_NOTNULL().
1639//
1640// In C++11, all cases can be handled by a single function. Since the value
1641// category of the argument is preserved (also for rvalue references),
1642// member initializer lists like the one below will compile correctly:
1643//
1644// Foo()
1645// : x_(CHECK_NOTNULL(MethodReturningUniquePtr())) {}
1646template <typename T>
1647T CheckNotNull(const char* file, int line, const char* names, T&& t) {
1648 if (t == nullptr) {
1649 LogMessageFatal(file, line, new std::string(names));
1650 }
1651 return std::forward<T>(t);
1652}
1653
1654#else
1655
1656// A small helper for CHECK_NOTNULL().
1657template <typename T>
1658T* CheckNotNull(const char *file, int line, const char *names, T* t) {
1659 if (t == NULL) {
1660 LogMessageFatal(file, line, new std::string(names));
1661 }
1662 return t;
1663}
1664#endif
1665
1666// Allow folks to put a counter in the LOG_EVERY_X()'ed messages. This
1667// only works if ostream is a LogStream. If the ostream is not a
1668// LogStream you'll get an assert saying as much at runtime.
James Kuszmaulba0ac1a2022-08-12 16:29:30 -07001669GLOG_EXPORT std::ostream& operator<<(std::ostream &os,
Austin Schuh906616c2019-01-21 20:25:11 -08001670 const PRIVATE_Counter&);
1671
1672
1673// Derived class for PLOG*() above.
James Kuszmaulba0ac1a2022-08-12 16:29:30 -07001674class GLOG_EXPORT ErrnoLogMessage : public LogMessage {
Austin Schuh906616c2019-01-21 20:25:11 -08001675 public:
James Kuszmaulba0ac1a2022-08-12 16:29:30 -07001676 ErrnoLogMessage(const char* file, int line, LogSeverity severity, int64 ctr,
Austin Schuh906616c2019-01-21 20:25:11 -08001677 void (LogMessage::*send_method)());
1678
1679 // Postpends ": strerror(errno) [errno]".
1680 ~ErrnoLogMessage();
1681
1682 private:
1683 ErrnoLogMessage(const ErrnoLogMessage&);
1684 void operator=(const ErrnoLogMessage&);
1685};
1686
1687
Austin Schuh906616c2019-01-21 20:25:11 -08001688// Flushes all log files that contains messages that are at least of
1689// the specified severity level. Thread-safe.
James Kuszmaulba0ac1a2022-08-12 16:29:30 -07001690GLOG_EXPORT void FlushLogFiles(LogSeverity min_severity);
Austin Schuh906616c2019-01-21 20:25:11 -08001691
1692// Flushes all log files that contains messages that are at least of
1693// the specified severity level. Thread-hostile because it ignores
1694// locking -- used for catastrophic failures.
James Kuszmaulba0ac1a2022-08-12 16:29:30 -07001695GLOG_EXPORT void FlushLogFilesUnsafe(LogSeverity min_severity);
Austin Schuh906616c2019-01-21 20:25:11 -08001696
1697//
1698// Set the destination to which a particular severity level of log
1699// messages is sent. If base_filename is "", it means "don't log this
1700// severity". Thread-safe.
1701//
James Kuszmaulba0ac1a2022-08-12 16:29:30 -07001702GLOG_EXPORT void SetLogDestination(LogSeverity severity,
Austin Schuh906616c2019-01-21 20:25:11 -08001703 const char* base_filename);
1704
1705//
1706// Set the basename of the symlink to the latest log file at a given
1707// severity. If symlink_basename is empty, do not make a symlink. If
1708// you don't call this function, the symlink basename is the
1709// invocation name of the program. Thread-safe.
1710//
James Kuszmaulba0ac1a2022-08-12 16:29:30 -07001711GLOG_EXPORT void SetLogSymlink(LogSeverity severity,
Austin Schuh906616c2019-01-21 20:25:11 -08001712 const char* symlink_basename);
1713
1714//
1715// Used to send logs to some other kind of destination
1716// Users should subclass LogSink and override send to do whatever they want.
1717// Implementations must be thread-safe because a shared instance will
1718// be called from whichever thread ran the LOG(XXX) line.
James Kuszmaulba0ac1a2022-08-12 16:29:30 -07001719class GLOG_EXPORT LogSink {
Austin Schuh906616c2019-01-21 20:25:11 -08001720 public:
1721 virtual ~LogSink();
1722
1723 // Sink's logging logic (message_len is such as to exclude '\n' at the end).
1724 // This method can't use LOG() or CHECK() as logging system mutex(s) are held
1725 // during this call.
1726 virtual void send(LogSeverity severity, const char* full_filename,
1727 const char* base_filename, int line,
James Kuszmaulba0ac1a2022-08-12 16:29:30 -07001728 const LogMessageTime& logmsgtime, const char* message,
1729 size_t message_len);
1730 // Provide an overload for compatibility purposes
1731 GLOG_DEPRECATED
1732 virtual void send(LogSeverity severity, const char* full_filename,
1733 const char* base_filename, int line, const std::tm* t,
1734 const char* message, size_t message_len);
Austin Schuh906616c2019-01-21 20:25:11 -08001735
1736 // Redefine this to implement waiting for
1737 // the sink's logging logic to complete.
1738 // It will be called after each send() returns,
1739 // but before that LogMessage exits or crashes.
1740 // By default this function does nothing.
1741 // Using this function one can implement complex logic for send()
1742 // that itself involves logging; and do all this w/o causing deadlocks and
1743 // inconsistent rearrangement of log messages.
1744 // E.g. if a LogSink has thread-specific actions, the send() method
1745 // can simply add the message to a queue and wake up another thread that
1746 // handles real logging while itself making some LOG() calls;
1747 // WaitTillSent() can be implemented to wait for that logic to complete.
1748 // See our unittest for an example.
1749 virtual void WaitTillSent();
1750
1751 // Returns the normal text output of the log message.
1752 // Can be useful to implement send().
1753 static std::string ToString(LogSeverity severity, const char* file, int line,
James Kuszmaulba0ac1a2022-08-12 16:29:30 -07001754 const LogMessageTime &logmsgtime,
Austin Schuh906616c2019-01-21 20:25:11 -08001755 const char* message, size_t message_len);
1756};
1757
1758// Add or remove a LogSink as a consumer of logging data. Thread-safe.
James Kuszmaulba0ac1a2022-08-12 16:29:30 -07001759GLOG_EXPORT void AddLogSink(LogSink *destination);
1760GLOG_EXPORT void RemoveLogSink(LogSink *destination);
Austin Schuh906616c2019-01-21 20:25:11 -08001761
1762//
1763// Specify an "extension" added to the filename specified via
1764// SetLogDestination. This applies to all severity levels. It's
1765// often used to append the port we're listening on to the logfile
1766// name. Thread-safe.
1767//
James Kuszmaulba0ac1a2022-08-12 16:29:30 -07001768GLOG_EXPORT void SetLogFilenameExtension(
Austin Schuh906616c2019-01-21 20:25:11 -08001769 const char* filename_extension);
1770
1771//
1772// Make it so that all log messages of at least a particular severity
1773// are logged to stderr (in addition to logging to the usual log
1774// file(s)). Thread-safe.
1775//
James Kuszmaulba0ac1a2022-08-12 16:29:30 -07001776GLOG_EXPORT void SetStderrLogging(LogSeverity min_severity);
Austin Schuh906616c2019-01-21 20:25:11 -08001777
1778//
1779// Make it so that all log messages go only to stderr. Thread-safe.
1780//
James Kuszmaulba0ac1a2022-08-12 16:29:30 -07001781GLOG_EXPORT void LogToStderr();
Austin Schuh906616c2019-01-21 20:25:11 -08001782
1783//
1784// Make it so that all log messages of at least a particular severity are
1785// logged via email to a list of addresses (in addition to logging to the
1786// usual log file(s)). The list of addresses is just a string containing
1787// the email addresses to send to (separated by spaces, say). Thread-safe.
1788//
James Kuszmaulba0ac1a2022-08-12 16:29:30 -07001789GLOG_EXPORT void SetEmailLogging(LogSeverity min_severity,
Austin Schuh906616c2019-01-21 20:25:11 -08001790 const char* addresses);
1791
1792// A simple function that sends email. dest is a commma-separated
1793// list of addressess. Thread-safe.
James Kuszmaulba0ac1a2022-08-12 16:29:30 -07001794GLOG_EXPORT bool SendEmail(const char* dest, const char* subject,
1795 const char* body);
Austin Schuh906616c2019-01-21 20:25:11 -08001796
James Kuszmaulba0ac1a2022-08-12 16:29:30 -07001797GLOG_EXPORT const std::vector<std::string>& GetLoggingDirectories();
Austin Schuh906616c2019-01-21 20:25:11 -08001798
1799// For tests only: Clear the internal [cached] list of logging directories to
1800// force a refresh the next time GetLoggingDirectories is called.
1801// Thread-hostile.
1802void TestOnly_ClearLoggingDirectoriesList();
1803
1804// Returns a set of existing temporary directories, which will be a
James Kuszmaulba0ac1a2022-08-12 16:29:30 -07001805// subset of the directories returned by GetLoggingDirectories().
Austin Schuh906616c2019-01-21 20:25:11 -08001806// Thread-safe.
James Kuszmaulba0ac1a2022-08-12 16:29:30 -07001807GLOG_EXPORT void GetExistingTempDirectories(
Austin Schuh906616c2019-01-21 20:25:11 -08001808 std::vector<std::string>* list);
1809
1810// Print any fatal message again -- useful to call from signal handler
1811// so that the last thing in the output is the fatal message.
1812// Thread-hostile, but a race is unlikely.
James Kuszmaulba0ac1a2022-08-12 16:29:30 -07001813GLOG_EXPORT void ReprintFatalMessage();
Austin Schuh906616c2019-01-21 20:25:11 -08001814
1815// Truncate a log file that may be the append-only output of multiple
1816// processes and hence can't simply be renamed/reopened (typically a
1817// stdout/stderr). If the file "path" is > "limit" bytes, copy the
1818// last "keep" bytes to offset 0 and truncate the rest. Since we could
1819// be racing with other writers, this approach has the potential to
1820// lose very small amounts of data. For security, only follow symlinks
1821// if the path is /proc/self/fd/*
James Kuszmaulba0ac1a2022-08-12 16:29:30 -07001822GLOG_EXPORT void TruncateLogFile(const char* path, uint64 limit, uint64 keep);
Austin Schuh906616c2019-01-21 20:25:11 -08001823
1824// Truncate stdout and stderr if they are over the value specified by
1825// --max_log_size; keep the final 1MB. This function has the same
1826// race condition as TruncateLogFile.
James Kuszmaulba0ac1a2022-08-12 16:29:30 -07001827GLOG_EXPORT void TruncateStdoutStderr();
Austin Schuh906616c2019-01-21 20:25:11 -08001828
1829// Return the string representation of the provided LogSeverity level.
1830// Thread-safe.
James Kuszmaulba0ac1a2022-08-12 16:29:30 -07001831GLOG_EXPORT const char* GetLogSeverityName(LogSeverity severity);
Austin Schuh906616c2019-01-21 20:25:11 -08001832
1833// ---------------------------------------------------------------------
1834// Implementation details that are not useful to most clients
1835// ---------------------------------------------------------------------
1836
1837// A Logger is the interface used by logging modules to emit entries
1838// to a log. A typical implementation will dump formatted data to a
1839// sequence of files. We also provide interfaces that will forward
1840// the data to another thread so that the invoker never blocks.
1841// Implementations should be thread-safe since the logging system
1842// will write to them from multiple threads.
1843
1844namespace base {
1845
James Kuszmaulba0ac1a2022-08-12 16:29:30 -07001846class GLOG_EXPORT Logger {
Austin Schuh906616c2019-01-21 20:25:11 -08001847 public:
1848 virtual ~Logger();
1849
1850 // Writes "message[0,message_len-1]" corresponding to an event that
1851 // occurred at "timestamp". If "force_flush" is true, the log file
1852 // is flushed immediately.
1853 //
1854 // The input message has already been formatted as deemed
1855 // appropriate by the higher level logging facility. For example,
1856 // textual log messages already contain timestamps, and the
1857 // file:linenumber header.
1858 virtual void Write(bool force_flush,
1859 time_t timestamp,
1860 const char* message,
James Kuszmaulba0ac1a2022-08-12 16:29:30 -07001861 size_t message_len) = 0;
Austin Schuh906616c2019-01-21 20:25:11 -08001862
1863 // Flush any buffered messages
1864 virtual void Flush() = 0;
1865
1866 // Get the current LOG file size.
1867 // The returned value is approximate since some
1868 // logged data may not have been flushed to disk yet.
1869 virtual uint32 LogSize() = 0;
1870};
1871
1872// Get the logger for the specified severity level. The logger
1873// remains the property of the logging module and should not be
1874// deleted by the caller. Thread-safe.
James Kuszmaulba0ac1a2022-08-12 16:29:30 -07001875extern GLOG_EXPORT Logger* GetLogger(LogSeverity level);
Austin Schuh906616c2019-01-21 20:25:11 -08001876
1877// Set the logger for the specified severity level. The logger
1878// becomes the property of the logging module and should not
1879// be deleted by the caller. Thread-safe.
James Kuszmaulba0ac1a2022-08-12 16:29:30 -07001880extern GLOG_EXPORT void SetLogger(LogSeverity level, Logger* logger);
Austin Schuh906616c2019-01-21 20:25:11 -08001881
1882}
1883
1884// glibc has traditionally implemented two incompatible versions of
1885// strerror_r(). There is a poorly defined convention for picking the
1886// version that we want, but it is not clear whether it even works with
1887// all versions of glibc.
1888// So, instead, we provide this wrapper that automatically detects the
1889// version that is in use, and then implements POSIX semantics.
1890// N.B. In addition to what POSIX says, we also guarantee that "buf" will
1891// be set to an empty string, if this function failed. This means, in most
1892// cases, you do not need to check the error code and you can directly
1893// use the value of "buf". It will never have an undefined value.
1894// DEPRECATED: Use StrError(int) instead.
James Kuszmaulba0ac1a2022-08-12 16:29:30 -07001895GLOG_EXPORT int posix_strerror_r(int err, char *buf, size_t len);
Austin Schuh906616c2019-01-21 20:25:11 -08001896
1897// A thread-safe replacement for strerror(). Returns a string describing the
1898// given POSIX error code.
James Kuszmaulba0ac1a2022-08-12 16:29:30 -07001899GLOG_EXPORT std::string StrError(int err);
Austin Schuh906616c2019-01-21 20:25:11 -08001900
1901// A class for which we define operator<<, which does nothing.
James Kuszmaulba0ac1a2022-08-12 16:29:30 -07001902class GLOG_EXPORT NullStream : public LogMessage::LogStream {
Austin Schuh906616c2019-01-21 20:25:11 -08001903 public:
1904 // Initialize the LogStream so the messages can be written somewhere
1905 // (they'll never be actually displayed). This will be needed if a
1906 // NullStream& is implicitly converted to LogStream&, in which case
1907 // the overloaded NullStream::operator<< will not be invoked.
1908 NullStream() : LogMessage::LogStream(message_buffer_, 1, 0) { }
1909 NullStream(const char* /*file*/, int /*line*/,
1910 const CheckOpString& /*result*/) :
1911 LogMessage::LogStream(message_buffer_, 1, 0) { }
1912 NullStream &stream() { return *this; }
1913 private:
1914 // A very short buffer for messages (which we discard anyway). This
1915 // will be needed if NullStream& converted to LogStream& (e.g. as a
1916 // result of a conditional expression).
1917 char message_buffer_[2];
1918};
1919
1920// Do nothing. This operator is inline, allowing the message to be
1921// compiled away. The message will not be compiled away if we do
1922// something like (flag ? LOG(INFO) : LOG(ERROR)) << message; when
1923// SKIP_LOG=WARNING. In those cases, NullStream will be implicitly
1924// converted to LogStream and the message will be computed and then
1925// quietly discarded.
1926template<class T>
1927inline NullStream& operator<<(NullStream &str, const T &) { return str; }
1928
1929// Similar to NullStream, but aborts the program (without stack
1930// trace), like LogMessageFatal.
James Kuszmaulba0ac1a2022-08-12 16:29:30 -07001931class GLOG_EXPORT NullStreamFatal : public NullStream {
Austin Schuh906616c2019-01-21 20:25:11 -08001932 public:
1933 NullStreamFatal() { }
1934 NullStreamFatal(const char* file, int line, const CheckOpString& result) :
1935 NullStream(file, line, result) { }
James Kuszmaulba0ac1a2022-08-12 16:29:30 -07001936#if defined(_MSC_VER)
1937#pragma warning(push)
1938#pragma warning(disable : 4722)
1939#endif // _MSC_VER
1940 @ac_cv___attribute___noreturn@ ~NullStreamFatal() throw () { _exit(EXIT_FAILURE); }
1941#if defined(_MSC_VER)
1942#pragma warning(pop)
1943#endif // _MSC_VER
Austin Schuh906616c2019-01-21 20:25:11 -08001944};
1945
1946// Install a signal handler that will dump signal information and a stack
1947// trace when the program crashes on certain signals. We'll install the
1948// signal handler for the following signals.
1949//
1950// SIGSEGV, SIGILL, SIGFPE, SIGABRT, SIGBUS, and SIGTERM.
1951//
1952// By default, the signal handler will write the failure dump to the
1953// standard error. You can customize the destination by installing your
1954// own writer function by InstallFailureWriter() below.
1955//
1956// Note on threading:
1957//
1958// The function should be called before threads are created, if you want
1959// to use the failure signal handler for all threads. The stack trace
1960// will be shown only for the thread that receives the signal. In other
1961// words, stack traces of other threads won't be shown.
James Kuszmaulba0ac1a2022-08-12 16:29:30 -07001962GLOG_EXPORT void InstallFailureSignalHandler();
Austin Schuh906616c2019-01-21 20:25:11 -08001963
1964// Installs a function that is used for writing the failure dump. "data"
1965// is the pointer to the beginning of a message to be written, and "size"
1966// is the size of the message. You should not expect the data is
1967// terminated with '\0'.
James Kuszmaulba0ac1a2022-08-12 16:29:30 -07001968GLOG_EXPORT void InstallFailureWriter(
1969 void (*writer)(const char* data, size_t size));
Austin Schuh906616c2019-01-21 20:25:11 -08001970
1971@ac_google_end_namespace@
1972
James Kuszmaulba0ac1a2022-08-12 16:29:30 -07001973#pragma pop_macro("DECLARE_VARIABLE")
1974#pragma pop_macro("DECLARE_bool")
1975#pragma pop_macro("DECLARE_string")
1976#pragma pop_macro("DECLARE_int32")
1977#pragma pop_macro("DECLARE_uint32")
1978
1979#endif // GLOG_LOGGING_H