xref: /aosp_15_r20/external/abseil-cpp/absl/log/log.h (revision 9356374a3709195abf420251b3e825997ff56c0f)
1 // Copyright 2022 The Abseil Authors.
2 //
3 // Licensed under the Apache License, Version 2.0 (the "License");
4 // you may not use this file except in compliance with the License.
5 // You may obtain a copy of the License at
6 //
7 //      https://www.apache.org/licenses/LICENSE-2.0
8 //
9 // Unless required by applicable law or agreed to in writing, software
10 // distributed under the License is distributed on an "AS IS" BASIS,
11 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 // See the License for the specific language governing permissions and
13 // limitations under the License.
14 //
15 // -----------------------------------------------------------------------------
16 // File: log/log.h
17 // -----------------------------------------------------------------------------
18 //
19 // This header declares a family of LOG macros.
20 //
21 // Basic invocation looks like this:
22 //
23 //   LOG(INFO) << "Found " << num_cookies << " cookies";
24 //
25 // Most `LOG` macros take a severity level argument.  The severity levels are
26 // `INFO`, `WARNING`, `ERROR`, and `FATAL`.  They are defined
27 // in absl/base/log_severity.h.
28 // * The `FATAL` severity level terminates the program with a stack trace after
29 //   logging its message.  Error handlers registered with `RunOnFailure`
30 //   (process_state.h) are run, but exit handlers registered with `atexit(3)`
31 //   are not.
32 // * The `QFATAL` pseudo-severity level is equivalent to `FATAL` but triggers
33 //   quieter termination messages, e.g. without a full stack trace, and skips
34 //   running registered error handlers.
35 // * The `DFATAL` pseudo-severity level is defined as `FATAL` in debug mode and
36 //   as `ERROR` otherwise.
37 // Some preprocessor shenanigans are used to ensure that e.g. `LOG(INFO)` has
38 // the same meaning even if a local symbol or preprocessor macro named `INFO` is
39 // defined.  To specify a severity level using an expression instead of a
40 // literal, use `LEVEL(expr)`.
41 // Example:
42 //
43 //   LOG(LEVEL(stale ? absl::LogSeverity::kWarning : absl::LogSeverity::kInfo))
44 //       << "Cookies are " << days << " days old";
45 
46 // `LOG` macros evaluate to an unterminated statement.  The value at the end of
47 // the statement supports some chainable methods:
48 //
49 //   * .AtLocation(absl::string_view file, int line)
50 //     .AtLocation(absl::SourceLocation loc)
51 //     Overrides the location inferred from the callsite.  The string pointed to
52 //     by `file` must be valid until the end of the statement.
53 //   * .NoPrefix()
54 //     Omits the prefix from this line.  The prefix includes metadata about the
55 //     logged data such as source code location and timestamp.
56 //   * .WithVerbosity(int verbose_level)
57 //     Sets the verbosity field of the logged message as if it was logged by
58 //     `VLOG(verbose_level)`.  Unlike `VLOG`, this method does not affect
59 //     evaluation of the statement when the specified `verbose_level` has been
60 //     disabled.  The only effect is on `LogSink` implementations which make use
61 //     of the `absl::LogSink::verbosity()` value.  The value
62 //     `absl::LogEntry::kNoVerbosityLevel` can be specified to mark the message
63 //     not verbose.
64 //   * .WithTimestamp(absl::Time timestamp)
65 //     Uses the specified timestamp instead of one collected at the time of
66 //     execution.
67 //   * .WithThreadID(absl::LogEntry::tid_t tid)
68 //     Uses the specified thread ID instead of one collected at the time of
69 //     execution.
70 //   * .WithMetadataFrom(const absl::LogEntry &entry)
71 //     Copies all metadata (but no data) from the specified `absl::LogEntry`.
72 //     This can be used to change the severity of a message, but it has some
73 //     limitations:
74 //     * `ABSL_MIN_LOG_LEVEL` is evaluated against the severity passed into
75 //       `LOG` (or the implicit `FATAL` level of `CHECK`).
76 //     * `LOG(FATAL)` and `CHECK` terminate the process unconditionally, even if
77 //       the severity is changed later.
78 //     `.WithMetadataFrom(entry)` should almost always be used in combination
79 //     with `LOG(LEVEL(entry.log_severity()))`.
80 //   * .WithPerror()
81 //     Appends to the logged message a colon, a space, a textual description of
82 //     the current value of `errno` (as by `strerror(3)`), and the numerical
83 //     value of `errno`.
84 //   * .ToSinkAlso(absl::LogSink* sink)
85 //     Sends this message to `*sink` in addition to whatever other sinks it
86 //     would otherwise have been sent to.  `sink` must not be null.
87 //   * .ToSinkOnly(absl::LogSink* sink)
88 //     Sends this message to `*sink` and no others.  `sink` must not be null.
89 //
90 // No interfaces in this header are async-signal-safe; their use in signal
91 // handlers is unsupported and may deadlock your program or eat your lunch.
92 //
93 // Many logging statements are inherently conditional.  For example,
94 // `LOG_IF(INFO, !foo)` does nothing if `foo` is true.  Even seemingly
95 // unconditional statements like `LOG(INFO)` might be disabled at
96 // compile-time to minimize binary size or for security reasons.
97 //
98 // * Except for the condition in a `CHECK` or `QCHECK` statement, programs must
99 //   not rely on evaluation of expressions anywhere in logging statements for
100 //   correctness.  For example, this is ok:
101 //
102 //     CHECK((fp = fopen("config.ini", "r")) != nullptr);
103 //
104 //   But this is probably not ok:
105 //
106 //     LOG(INFO) << "Server status: " << StartServerAndReturnStatusString();
107 //
108 //   The example below is bad too; the `i++` in the `LOG_IF` condition might
109 //   not be evaluated, resulting in an infinite loop:
110 //
111 //     for (int i = 0; i < 1000000;)
112 //       LOG_IF(INFO, i++ % 1000 == 0) << "Still working...";
113 //
114 // * Except where otherwise noted, conditions which cause a statement not to log
115 //   also cause expressions not to be evaluated.  Programs may rely on this for
116 //   performance reasons, e.g. by streaming the result of an expensive function
117 //   call into a `DLOG` or `LOG_EVERY_N` statement.
118 // * Care has been taken to ensure that expressions are parsed by the compiler
119 //   even if they are never evaluated.  This means that syntax errors will be
120 //   caught and variables will be considered used for the purposes of
121 //   unused-variable diagnostics.  For example, this statement won't compile
122 //   even if `INFO`-level logging has been compiled out:
123 //
124 //     int number_of_cakes = 40;
125 //     LOG(INFO) << "Number of cakes: " << number_of_cake;  // Note the typo!
126 //
127 //   Similarly, this won't produce unused-variable compiler diagnostics even
128 //   if `INFO`-level logging is compiled out:
129 //
130 //     {
131 //       char fox_line1[] = "Hatee-hatee-hatee-ho!";
132 //       LOG_IF(ERROR, false) << "The fox says " << fox_line1;
133 //       char fox_line2[] = "A-oo-oo-oo-ooo!";
134 //       LOG(INFO) << "The fox also says " << fox_line2;
135 //     }
136 //
137 //   This error-checking is not perfect; for example, symbols that have been
138 //   declared but not defined may not produce link errors if used in logging
139 //   statements that compile away.
140 //
141 // Expressions streamed into these macros are formatted using `operator<<` just
142 // as they would be if streamed into a `std::ostream`, however it should be
143 // noted that their actual type is unspecified.
144 //
145 // To implement a custom formatting operator for a type you own, there are two
146 // options: `AbslStringify()` or `std::ostream& operator<<(std::ostream&, ...)`.
147 // It is recommended that users make their types loggable through
148 // `AbslStringify()` as it is a universal stringification extension that also
149 // enables `absl::StrFormat` and `absl::StrCat` support. If both
150 // `AbslStringify()` and `std::ostream& operator<<(std::ostream&, ...)` are
151 // defined, `AbslStringify()` will be used.
152 //
153 // To use the `AbslStringify()` API, define a friend function template in your
154 // type's namespace with the following signature:
155 //
156 //   template <typename Sink>
157 //   void AbslStringify(Sink& sink, const UserDefinedType& value);
158 //
159 // `Sink` has the same interface as `absl::FormatSink`, but without
160 // `PutPaddedString()`.
161 //
162 // Example:
163 //
164 //   struct Point {
165 //     template <typename Sink>
166 //     friend void AbslStringify(Sink& sink, const Point& p) {
167 //       absl::Format(&sink, "(%v, %v)", p.x, p.y);
168 //     }
169 //
170 //     int x;
171 //     int y;
172 //   };
173 //
174 // To use `std::ostream& operator<<(std::ostream&, ...)`, define
175 // `std::ostream& operator<<(std::ostream&, ...)` in your type's namespace (for
176 // ADL) just as you would to stream it to `std::cout`.
177 //
178 // Currently `AbslStringify()` ignores output manipulators but this is not
179 // guaranteed behavior and may be subject to change in the future. If you would
180 // like guaranteed behavior regarding output manipulators, please use
181 // `std::ostream& operator<<(std::ostream&, ...)` to make custom types loggable
182 // instead.
183 //
184 // Those macros that support streaming honor output manipulators and `fmtflag`
185 // changes that output data (e.g. `std::ends`) or control formatting of data
186 // (e.g. `std::hex` and `std::fixed`), however flushing such a stream is
187 // ignored.  The message produced by a log statement is sent to registered
188 // `absl::LogSink` instances at the end of the statement; those sinks are
189 // responsible for their own flushing (e.g. to disk) semantics.
190 //
191 // Flag settings are not carried over from one `LOG` statement to the next; this
192 // is a bit different than e.g. `std::cout`:
193 //
194 //   LOG(INFO) << std::hex << 0xdeadbeef;  // logs "0xdeadbeef"
195 //   LOG(INFO) << 0xdeadbeef;              // logs "3735928559"
196 
197 #ifndef ABSL_LOG_LOG_H_
198 #define ABSL_LOG_LOG_H_
199 
200 #include "absl/log/internal/log_impl.h"
201 
202 // LOG()
203 //
204 // `LOG` takes a single argument which is a severity level.  Data streamed in
205 // comprise the logged message.
206 // Example:
207 //
208 //   LOG(INFO) << "Found " << num_cookies << " cookies";
209 #define LOG(severity) ABSL_LOG_INTERNAL_LOG_IMPL(_##severity)
210 
211 // PLOG()
212 //
213 // `PLOG` behaves like `LOG` except that a description of the current state of
214 // `errno` is appended to the streamed message.
215 #define PLOG(severity) ABSL_LOG_INTERNAL_PLOG_IMPL(_##severity)
216 
217 // DLOG()
218 //
219 // `DLOG` behaves like `LOG` in debug mode (i.e. `#ifndef NDEBUG`).  Otherwise
220 // it compiles away and does nothing.  Note that `DLOG(FATAL)` does not
221 // terminate the program if `NDEBUG` is defined.
222 #define DLOG(severity) ABSL_LOG_INTERNAL_DLOG_IMPL(_##severity)
223 
224 // `VLOG` uses numeric levels to provide verbose logging that can configured at
225 // runtime, including at a per-module level.  `VLOG` statements are logged at
226 // `INFO` severity if they are logged at all; the numeric levels are on a
227 // different scale than the proper severity levels.  Positive levels are
228 // disabled by default.  Negative levels should not be used.
229 // Example:
230 //
231 //   VLOG(1) << "I print when you run the program with --v=1 or higher";
232 //   VLOG(2) << "I print when you run the program with --v=2 or higher";
233 //
234 // See vlog_is_on.h for further documentation, including the usage of the
235 // --vmodule flag to log at different levels in different source files.
236 //
237 // `VLOG` does not produce any output when verbose logging is not enabled.
238 // However, simply testing whether verbose logging is enabled can be expensive.
239 // If you don't intend to enable verbose logging in non-debug builds, consider
240 // using `DVLOG` instead.
241 #define VLOG(severity) ABSL_LOG_INTERNAL_VLOG_IMPL(severity)
242 
243 // `DVLOG` behaves like `VLOG` in debug mode (i.e. `#ifndef NDEBUG`).
244 // Otherwise, it compiles away and does nothing.
245 #define DVLOG(severity) ABSL_LOG_INTERNAL_DVLOG_IMPL(severity)
246 
247 // `LOG_IF` and friends add a second argument which specifies a condition.  If
248 // the condition is false, nothing is logged.
249 // Example:
250 //
251 //   LOG_IF(INFO, num_cookies > 10) << "Got lots of cookies";
252 //
253 // There is no `VLOG_IF` because the order of evaluation of the arguments is
254 // ambiguous and the alternate spelling with an `if`-statement is trivial.
255 #define LOG_IF(severity, condition) \
256   ABSL_LOG_INTERNAL_LOG_IF_IMPL(_##severity, condition)
257 #define PLOG_IF(severity, condition) \
258   ABSL_LOG_INTERNAL_PLOG_IF_IMPL(_##severity, condition)
259 #define DLOG_IF(severity, condition) \
260   ABSL_LOG_INTERNAL_DLOG_IF_IMPL(_##severity, condition)
261 
262 // LOG_EVERY_N
263 //
264 // An instance of `LOG_EVERY_N` increments a hidden zero-initialized counter
265 // every time execution passes through it and logs the specified message when
266 // the counter's value is a multiple of `n`, doing nothing otherwise.  Each
267 // instance has its own counter.  The counter's value can be logged by streaming
268 // the symbol `COUNTER`.  `LOG_EVERY_N` is thread-safe.
269 // Example:
270 //
271 //   LOG_EVERY_N(WARNING, 1000) << "Got a packet with a bad CRC (" << COUNTER
272 //                              << " total)";
273 #define LOG_EVERY_N(severity, n) \
274   ABSL_LOG_INTERNAL_LOG_EVERY_N_IMPL(_##severity, n)
275 
276 // LOG_FIRST_N
277 //
278 // `LOG_FIRST_N` behaves like `LOG_EVERY_N` except that the specified message is
279 // logged when the counter's value is less than `n`.  `LOG_FIRST_N` is
280 // thread-safe.
281 #define LOG_FIRST_N(severity, n) \
282   ABSL_LOG_INTERNAL_LOG_FIRST_N_IMPL(_##severity, n)
283 
284 // LOG_EVERY_POW_2
285 //
286 // `LOG_EVERY_POW_2` behaves like `LOG_EVERY_N` except that the specified
287 // message is logged when the counter's value is a power of 2.
288 // `LOG_EVERY_POW_2` is thread-safe.
289 #define LOG_EVERY_POW_2(severity) \
290   ABSL_LOG_INTERNAL_LOG_EVERY_POW_2_IMPL(_##severity)
291 
292 // LOG_EVERY_N_SEC
293 //
294 // An instance of `LOG_EVERY_N_SEC` uses a hidden state variable to log the
295 // specified message at most once every `n_seconds`.  A hidden counter of
296 // executions (whether a message is logged or not) is also maintained and can be
297 // logged by streaming the symbol `COUNTER`.  `LOG_EVERY_N_SEC` is thread-safe.
298 // Example:
299 //
300 //   LOG_EVERY_N_SEC(INFO, 2.5) << "Got " << COUNTER << " cookies so far";
301 #define LOG_EVERY_N_SEC(severity, n_seconds) \
302   ABSL_LOG_INTERNAL_LOG_EVERY_N_SEC_IMPL(_##severity, n_seconds)
303 
304 #define PLOG_EVERY_N(severity, n) \
305   ABSL_LOG_INTERNAL_PLOG_EVERY_N_IMPL(_##severity, n)
306 #define PLOG_FIRST_N(severity, n) \
307   ABSL_LOG_INTERNAL_PLOG_FIRST_N_IMPL(_##severity, n)
308 #define PLOG_EVERY_POW_2(severity) \
309   ABSL_LOG_INTERNAL_PLOG_EVERY_POW_2_IMPL(_##severity)
310 #define PLOG_EVERY_N_SEC(severity, n_seconds) \
311   ABSL_LOG_INTERNAL_PLOG_EVERY_N_SEC_IMPL(_##severity, n_seconds)
312 
313 #define DLOG_EVERY_N(severity, n) \
314   ABSL_LOG_INTERNAL_DLOG_EVERY_N_IMPL(_##severity, n)
315 #define DLOG_FIRST_N(severity, n) \
316   ABSL_LOG_INTERNAL_DLOG_FIRST_N_IMPL(_##severity, n)
317 #define DLOG_EVERY_POW_2(severity) \
318   ABSL_LOG_INTERNAL_DLOG_EVERY_POW_2_IMPL(_##severity)
319 #define DLOG_EVERY_N_SEC(severity, n_seconds) \
320   ABSL_LOG_INTERNAL_DLOG_EVERY_N_SEC_IMPL(_##severity, n_seconds)
321 
322 #define VLOG_EVERY_N(severity, n) \
323   ABSL_LOG_INTERNAL_VLOG_EVERY_N_IMPL(severity, n)
324 #define VLOG_FIRST_N(severity, n) \
325   ABSL_LOG_INTERNAL_VLOG_FIRST_N_IMPL(severity, n)
326 #define VLOG_EVERY_POW_2(severity) \
327   ABSL_LOG_INTERNAL_VLOG_EVERY_POW_2_IMPL(severity)
328 #define VLOG_EVERY_N_SEC(severity, n_seconds) \
329   ABSL_LOG_INTERNAL_VLOG_EVERY_N_SEC_IMPL(severity, n_seconds)
330 
331 // `LOG_IF_EVERY_N` and friends behave as the corresponding `LOG_EVERY_N`
332 // but neither increment a counter nor log a message if condition is false (as
333 // `LOG_IF`).
334 // Example:
335 //
336 //   LOG_IF_EVERY_N(INFO, (size > 1024), 10) << "Got the " << COUNTER
337 //                                           << "th big cookie";
338 #define LOG_IF_EVERY_N(severity, condition, n) \
339   ABSL_LOG_INTERNAL_LOG_IF_EVERY_N_IMPL(_##severity, condition, n)
340 #define LOG_IF_FIRST_N(severity, condition, n) \
341   ABSL_LOG_INTERNAL_LOG_IF_FIRST_N_IMPL(_##severity, condition, n)
342 #define LOG_IF_EVERY_POW_2(severity, condition) \
343   ABSL_LOG_INTERNAL_LOG_IF_EVERY_POW_2_IMPL(_##severity, condition)
344 #define LOG_IF_EVERY_N_SEC(severity, condition, n_seconds) \
345   ABSL_LOG_INTERNAL_LOG_IF_EVERY_N_SEC_IMPL(_##severity, condition, n_seconds)
346 
347 #define PLOG_IF_EVERY_N(severity, condition, n) \
348   ABSL_LOG_INTERNAL_PLOG_IF_EVERY_N_IMPL(_##severity, condition, n)
349 #define PLOG_IF_FIRST_N(severity, condition, n) \
350   ABSL_LOG_INTERNAL_PLOG_IF_FIRST_N_IMPL(_##severity, condition, n)
351 #define PLOG_IF_EVERY_POW_2(severity, condition) \
352   ABSL_LOG_INTERNAL_PLOG_IF_EVERY_POW_2_IMPL(_##severity, condition)
353 #define PLOG_IF_EVERY_N_SEC(severity, condition, n_seconds) \
354   ABSL_LOG_INTERNAL_PLOG_IF_EVERY_N_SEC_IMPL(_##severity, condition, n_seconds)
355 
356 #define DLOG_IF_EVERY_N(severity, condition, n) \
357   ABSL_LOG_INTERNAL_DLOG_IF_EVERY_N_IMPL(_##severity, condition, n)
358 #define DLOG_IF_FIRST_N(severity, condition, n) \
359   ABSL_LOG_INTERNAL_DLOG_IF_FIRST_N_IMPL(_##severity, condition, n)
360 #define DLOG_IF_EVERY_POW_2(severity, condition) \
361   ABSL_LOG_INTERNAL_DLOG_IF_EVERY_POW_2_IMPL(_##severity, condition)
362 #define DLOG_IF_EVERY_N_SEC(severity, condition, n_seconds) \
363   ABSL_LOG_INTERNAL_DLOG_IF_EVERY_N_SEC_IMPL(_##severity, condition, n_seconds)
364 
365 #endif  // ABSL_LOG_LOG_H_
366