blob: 9aa2bf29012dbf9310b602b8a54ac7862eb9fa28 [file] [log] [blame]
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001/*
2 * Copyright 2004 The WebRTC Project Authors. All rights reserved.
3 *
4 * Use of this source code is governed by a BSD-style license
5 * that can be found in the LICENSE file in the root of the source
6 * tree. An additional intellectual property rights grant can be found
7 * in the file PATENTS. All contributing project authors may
8 * be found in the AUTHORS file in the root of the source tree.
9 */
10
Mirko Bonadei8ed8e562017-10-27 09:43:53 +020011// RTC_LOG(...) an ostream target that can be used to send formatted
henrike@webrtc.orgf0488722014-05-13 18:00:26 +000012// output to a variety of logging targets, such as debugger console, stderr,
Tommi0eefb4d2015-05-23 09:54:07 +020013// or any LogSink.
Mirko Bonadei8ed8e562017-10-27 09:43:53 +020014// The severity level passed as the first argument to the logging
henrike@webrtc.orgf0488722014-05-13 18:00:26 +000015// functions is used as a filter, to limit the verbosity of the logging.
Mirko Bonadei8ed8e562017-10-27 09:43:53 +020016// Static members of LogMessage documented below are used to control the
henrike@webrtc.orgf0488722014-05-13 18:00:26 +000017// verbosity and target of the output.
Mirko Bonadei8ed8e562017-10-27 09:43:53 +020018// There are several variations on the RTC_LOG macro which facilitate logging
henrike@webrtc.orgf0488722014-05-13 18:00:26 +000019// of common error conditions, detailed below.
20
Mirko Bonadei8ed8e562017-10-27 09:43:53 +020021// RTC_LOG(sev) logs the given stream at severity "sev", which must be a
henrike@webrtc.orgf0488722014-05-13 18:00:26 +000022// compile-time constant of the LoggingSeverity type, without the namespace
23// prefix.
Mirko Bonadei8ed8e562017-10-27 09:43:53 +020024// RTC_LOG_V(sev) Like RTC_LOG(), but sev is a run-time variable of the
25// LoggingSeverity type (basically, it just doesn't prepend the namespace).
26// RTC_LOG_F(sev) Like RTC_LOG(), but includes the name of the current function.
27// RTC_LOG_T(sev) Like RTC_LOG(), but includes the this pointer.
28// RTC_LOG_T_F(sev) Like RTC_LOG_F(), but includes the this pointer.
Tommie51a0a82018-02-27 15:30:29 +010029// RTC_LOG_GLE(sev [, mod]) attempt to add a string description of the
30// HRESULT returned by GetLastError.
Mirko Bonadei8ed8e562017-10-27 09:43:53 +020031// RTC_LOG_ERRNO(sev) attempts to add a string description of an errno-derived
henrike@webrtc.orgf0488722014-05-13 18:00:26 +000032// error. errno and associated facilities exist on both Windows and POSIX,
33// but on Windows they only apply to the C/C++ runtime.
Mirko Bonadei8ed8e562017-10-27 09:43:53 +020034// RTC_LOG_ERR(sev) is an alias for the platform's normal error system, i.e.
35// _GLE on Windows and _ERRNO on POSIX.
henrike@webrtc.orgf0488722014-05-13 18:00:26 +000036// (The above three also all have _EX versions that let you specify the error
37// code, rather than using the last one.)
Mirko Bonadei8ed8e562017-10-27 09:43:53 +020038// RTC_LOG_E(sev, ctx, err, ...) logs a detailed error interpreted using the
henrike@webrtc.orgf0488722014-05-13 18:00:26 +000039// specified context.
Mirko Bonadei8ed8e562017-10-27 09:43:53 +020040// RTC_LOG_CHECK_LEVEL(sev) (and RTC_LOG_CHECK_LEVEL_V(sev)) can be used as a
41// test before performing expensive or sensitive operations whose sole
42// purpose is to output logging data at the desired level.
henrike@webrtc.orgf0488722014-05-13 18:00:26 +000043
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020044#ifndef RTC_BASE_LOGGING_H_
45#define RTC_BASE_LOGGING_H_
henrike@webrtc.orgf0488722014-05-13 18:00:26 +000046
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +020047#include <errno.h>
mostynbe38e4f62016-05-12 01:08:20 -070048
Markus Handellce1ff6f2020-07-08 08:52:48 +020049#include <atomic>
Jonas Olsson941a07c2018-09-13 10:07:07 +020050#include <sstream> // no-presubmit-check TODO(webrtc:8982)
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +020051#include <string>
Evan Shrubsole7765f9e2022-04-25 11:04:12 +020052#include <type_traits>
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +020053#include <utility>
54
Danil Chapovalove9041612021-02-22 12:43:39 +010055#include "absl/base/attributes.h"
Sebastian Janssonf4e085a2019-05-20 18:34:07 +020056#include "absl/meta/type_traits.h"
Jonas Olssonf2ce37c2018-09-12 15:32:47 +020057#include "absl/strings/string_view.h"
Mirko Bonadei96191f82022-08-03 08:12:33 +000058#include "absl/types/optional.h"
59#include "api/units/timestamp.h"
60#include "rtc_base/platform_thread_types.h"
Jonas Olssond8c50782018-09-07 11:21:28 +020061#include "rtc_base/strings/string_builder.h"
Karl Wibergcefc4652018-05-23 23:20:38 +020062#include "rtc_base/system/inline.h"
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +020063
Fredrik Solenbergb3d7cac2017-11-17 15:22:37 +010064#if !defined(NDEBUG) || defined(DLOG_ALWAYS_ON)
65#define RTC_DLOG_IS_ON 1
66#else
67#define RTC_DLOG_IS_ON 0
68#endif
69
Artem Titov6a4a1462019-11-26 16:24:46 +010070#if defined(RTC_DISABLE_LOGGING)
71#define RTC_LOG_ENABLED() 0
72#else
73#define RTC_LOG_ENABLED() 1
74#endif
75
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +020076namespace rtc {
77
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +020078//////////////////////////////////////////////////////////////////////
Harald Alvestrand57869da2022-03-09 10:52:14 +000079// The meanings of the levels are:
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +020080// LS_VERBOSE: This level is for data which we do not want to appear in the
81// normal debug log, but should appear in diagnostic logs.
82// LS_INFO: Chatty level used in debugging for all sorts of things, the default
83// in debug builds.
84// LS_WARNING: Something that may warrant investigation.
85// LS_ERROR: Something that should not have occurred.
86// LS_NONE: Don't log.
87enum LoggingSeverity {
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +020088 LS_VERBOSE,
89 LS_INFO,
90 LS_WARNING,
91 LS_ERROR,
92 LS_NONE,
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +020093};
94
95// LogErrorContext assists in interpreting the meaning of an error value.
96enum LogErrorContext {
97 ERRCTX_NONE,
Jonas Olssona4d87372019-07-05 19:08:33 +020098 ERRCTX_ERRNO, // System-local errno
99 ERRCTX_HRESULT, // Windows HRESULT
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200100
101 // Abbreviations for LOG_E macro
Jonas Olssona4d87372019-07-05 19:08:33 +0200102 ERRCTX_EN = ERRCTX_ERRNO, // LOG_E(sev, EN, x)
103 ERRCTX_HR = ERRCTX_HRESULT, // LOG_E(sev, HR, x)
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200104};
105
Danil Chapovalovb9f69022019-10-21 09:19:10 +0200106class LogMessage;
Mirko Bonadei96191f82022-08-03 08:12:33 +0000107
108// LogLineRef encapsulates all the information required to generate a log line.
109// It is used both internally to LogMessage but also as a parameter to
110// LogSink::OnLogMessage, allowing custom LogSinks to format the log in
111// the most flexible way.
112class LogLineRef {
113 public:
114 absl::string_view message() { return message_; }
115 absl::string_view filename() { return filename_; };
116 int line() { return line_; };
117 absl::optional<PlatformThreadId> thread_id() { return thread_id_; };
118 webrtc::Timestamp timestamp() { return timestamp_; };
119 absl::string_view tag() const { return tag_; };
120 LoggingSeverity severity() const { return severity_; }
121
122 std::string DefaultLogLine() const;
123
124 private:
125 friend class LogMessage;
126 void set_message(std::string message) { message_ = std::move(message); }
127 void set_filename(absl::string_view filename) { filename_ = filename; }
128 void set_line(int line) { line_ = line; }
129 void set_thread_id(absl::optional<PlatformThreadId> thread_id) {
130 thread_id_ = thread_id;
131 }
132 void set_timestamp(webrtc::Timestamp timestamp) { timestamp_ = timestamp; }
133 void set_tag(absl::string_view tag) { tag_ = tag; }
134 void set_severity(LoggingSeverity severity) { severity_ = severity; }
135
136 std::string message_;
137 absl::string_view filename_;
138 int line_ = 0;
139 absl::optional<PlatformThreadId> thread_id_;
140 webrtc::Timestamp timestamp_ = webrtc::Timestamp::MinusInfinity();
141 // The default Android debug output tag.
142 absl::string_view tag_ = "libjingle";
143 // The severity level of this message
144 LoggingSeverity severity_;
145};
146
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200147// Virtual sink interface that can receive log messages.
148class LogSink {
149 public:
150 LogSink() {}
151 virtual ~LogSink() {}
Paulina Hensmanf1e3cb42018-06-20 14:07:05 +0200152 virtual void OnLogMessage(const std::string& msg,
153 LoggingSeverity severity,
154 const char* tag);
Jiawei Ou3ea18782018-10-31 23:14:24 -0700155 virtual void OnLogMessage(const std::string& message,
156 LoggingSeverity severity);
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200157 virtual void OnLogMessage(const std::string& message) = 0;
Danil Chapovalovb9f69022019-10-21 09:19:10 +0200158
Ali Tofigh6364d082022-03-14 13:32:04 +0100159 virtual void OnLogMessage(absl::string_view msg,
160 LoggingSeverity severity,
161 const char* tag);
162 virtual void OnLogMessage(absl::string_view message,
163 LoggingSeverity severity);
164 virtual void OnLogMessage(absl::string_view message);
Mirko Bonadei96191f82022-08-03 08:12:33 +0000165 virtual void OnLogMessage(const LogLineRef& line);
Ali Tofigh6364d082022-03-14 13:32:04 +0100166
Danil Chapovalovb9f69022019-10-21 09:19:10 +0200167 private:
168 friend class ::rtc::LogMessage;
Artem Titov6a4a1462019-11-26 16:24:46 +0100169#if RTC_LOG_ENABLED()
Danil Chapovalovb9f69022019-10-21 09:19:10 +0200170 // Members for LogMessage class to keep linked list of the registered sinks.
171 LogSink* next_ = nullptr;
172 LoggingSeverity min_severity_;
Artem Titov6a4a1462019-11-26 16:24:46 +0100173#endif
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200174};
175
Karl Wibergcefc4652018-05-23 23:20:38 +0200176namespace webrtc_logging_impl {
177
178class LogMetadata {
179 public:
180 LogMetadata(const char* file, int line, LoggingSeverity severity)
181 : file_(file),
182 line_and_sev_(static_cast<uint32_t>(line) << 3 | severity) {}
183 LogMetadata() = default;
184
185 const char* File() const { return file_; }
186 int Line() const { return line_and_sev_ >> 3; }
187 LoggingSeverity Severity() const {
188 return static_cast<LoggingSeverity>(line_and_sev_ & 0x7);
189 }
190
191 private:
192 const char* file_;
193
194 // Line number and severity, the former in the most significant 29 bits, the
195 // latter in the least significant 3 bits. (This is an optimization; since
196 // both numbers are usually compile-time constants, this way we can load them
197 // both with a single instruction.)
198 uint32_t line_and_sev_;
199};
200static_assert(std::is_trivial<LogMetadata>::value, "");
201
202struct LogMetadataErr {
203 LogMetadata meta;
204 LogErrorContext err_ctx;
205 int err;
206};
207
208#ifdef WEBRTC_ANDROID
209struct LogMetadataTag {
210 LoggingSeverity severity;
211 const char* tag;
212};
213#endif
214
215enum class LogArgType : int8_t {
216 kEnd = 0,
217 kInt,
218 kLong,
219 kLongLong,
220 kUInt,
221 kULong,
222 kULongLong,
223 kDouble,
224 kLongDouble,
225 kCharP,
226 kStdString,
Jonas Olssonf2ce37c2018-09-12 15:32:47 +0200227 kStringView,
Karl Wibergcefc4652018-05-23 23:20:38 +0200228 kVoidP,
229 kLogMetadata,
230 kLogMetadataErr,
231#ifdef WEBRTC_ANDROID
232 kLogMetadataTag,
233#endif
234};
235
236// Wrapper for log arguments. Only ever make values of this type with the
237// MakeVal() functions.
238template <LogArgType N, typename T>
239struct Val {
240 static constexpr LogArgType Type() { return N; }
241 T GetVal() const { return val; }
242 T val;
243};
244
Sebastian Janssonb1138622019-04-11 16:48:15 +0200245// Case for when we need to construct a temp string and then print that.
246// (We can't use Val<CheckArgType::kStdString, const std::string*>
247// because we need somewhere to store the temp string.)
248struct ToStringVal {
Karl Wibergcefc4652018-05-23 23:20:38 +0200249 static constexpr LogArgType Type() { return LogArgType::kStdString; }
250 const std::string* GetVal() const { return &val; }
251 std::string val;
252};
253
254inline Val<LogArgType::kInt, int> MakeVal(int x) {
255 return {x};
256}
257inline Val<LogArgType::kLong, long> MakeVal(long x) {
258 return {x};
259}
260inline Val<LogArgType::kLongLong, long long> MakeVal(long long x) {
261 return {x};
262}
263inline Val<LogArgType::kUInt, unsigned int> MakeVal(unsigned int x) {
264 return {x};
265}
266inline Val<LogArgType::kULong, unsigned long> MakeVal(unsigned long x) {
267 return {x};
268}
269inline Val<LogArgType::kULongLong, unsigned long long> MakeVal(
270 unsigned long long x) {
271 return {x};
272}
273
274inline Val<LogArgType::kDouble, double> MakeVal(double x) {
275 return {x};
276}
277inline Val<LogArgType::kLongDouble, long double> MakeVal(long double x) {
278 return {x};
279}
280
281inline Val<LogArgType::kCharP, const char*> MakeVal(const char* x) {
282 return {x};
283}
284inline Val<LogArgType::kStdString, const std::string*> MakeVal(
285 const std::string& x) {
286 return {&x};
287}
Jonas Olssonf2ce37c2018-09-12 15:32:47 +0200288inline Val<LogArgType::kStringView, const absl::string_view*> MakeVal(
289 const absl::string_view& x) {
290 return {&x};
291}
Karl Wibergcefc4652018-05-23 23:20:38 +0200292
293inline Val<LogArgType::kVoidP, const void*> MakeVal(const void* x) {
294 return {x};
295}
296
297inline Val<LogArgType::kLogMetadata, LogMetadata> MakeVal(
298 const LogMetadata& x) {
299 return {x};
300}
301inline Val<LogArgType::kLogMetadataErr, LogMetadataErr> MakeVal(
302 const LogMetadataErr& x) {
303 return {x};
304}
305
Amit Hilbuch10c5a932019-03-18 13:09:18 -0700306// The enum class types are not implicitly convertible to arithmetic types.
Sebastian Janssonf4e085a2019-05-20 18:34:07 +0200307template <typename T,
308 absl::enable_if_t<std::is_enum<T>::value &&
309 !std::is_arithmetic<T>::value>* = nullptr>
310inline decltype(MakeVal(std::declval<absl::underlying_type_t<T>>())) MakeVal(
311 T x) {
312 return {static_cast<absl::underlying_type_t<T>>(x)};
Amit Hilbuch10c5a932019-03-18 13:09:18 -0700313}
314
Karl Wibergcefc4652018-05-23 23:20:38 +0200315#ifdef WEBRTC_ANDROID
316inline Val<LogArgType::kLogMetadataTag, LogMetadataTag> MakeVal(
317 const LogMetadataTag& x) {
318 return {x};
319}
320#endif
321
Sebastian Janssonf4e085a2019-05-20 18:34:07 +0200322template <typename T, class = void>
Sebastian Janssonb1138622019-04-11 16:48:15 +0200323struct has_to_log_string : std::false_type {};
324template <typename T>
Evan Shrubsole7765f9e2022-04-25 11:04:12 +0200325struct has_to_log_string<T,
326 absl::enable_if_t<std::is_convertible<
327 decltype(ToLogString(std::declval<T>())),
328 std::string>::value>> : std::true_type {};
329
330template <typename T, absl::enable_if_t<has_to_log_string<T>::value>* = nullptr>
331ToStringVal MakeVal(const T& x) {
332 return {ToLogString(x)};
333}
Sebastian Janssonb1138622019-04-11 16:48:15 +0200334
Karl Wibergcefc4652018-05-23 23:20:38 +0200335// Handle arbitrary types other than the above by falling back to stringstream.
336// TODO(bugs.webrtc.org/9278): Get rid of this overload when callers don't need
337// it anymore. No in-tree caller does, but some external callers still do.
338template <
339 typename T,
Sebastian Janssonf4e085a2019-05-20 18:34:07 +0200340 typename T1 = absl::decay_t<T>,
341 absl::enable_if_t<std::is_class<T1>::value &&
342 !std::is_same<T1, std::string>::value &&
343 !std::is_same<T1, LogMetadata>::value &&
344 !has_to_log_string<T1>::value &&
Karl Wibergcefc4652018-05-23 23:20:38 +0200345#ifdef WEBRTC_ANDROID
Sebastian Janssonf4e085a2019-05-20 18:34:07 +0200346 !std::is_same<T1, LogMetadataTag>::value &&
Karl Wibergcefc4652018-05-23 23:20:38 +0200347#endif
Sebastian Janssonf4e085a2019-05-20 18:34:07 +0200348 !std::is_same<T1, LogMetadataErr>::value>* = nullptr>
Sebastian Janssonb1138622019-04-11 16:48:15 +0200349ToStringVal MakeVal(const T& x) {
Karl Wibergcefc4652018-05-23 23:20:38 +0200350 std::ostringstream os; // no-presubmit-check TODO(webrtc:8982)
351 os << x;
352 return {os.str()};
353}
354
Artem Titov6a4a1462019-11-26 16:24:46 +0100355#if RTC_LOG_ENABLED()
Karl Wibergcefc4652018-05-23 23:20:38 +0200356void Log(const LogArgType* fmt, ...);
Artem Titov6a4a1462019-11-26 16:24:46 +0100357#else
358inline void Log(const LogArgType* fmt, ...) {
359 // Do nothing, shouldn't be invoked
360}
361#endif
Karl Wibergcefc4652018-05-23 23:20:38 +0200362
363// Ephemeral type that represents the result of the logging << operator.
364template <typename... Ts>
365class LogStreamer;
366
367// Base case: Before the first << argument.
368template <>
369class LogStreamer<> final {
370 public:
Amit Hilbuch10c5a932019-03-18 13:09:18 -0700371 template <typename U,
Sebastian Janssonf4e085a2019-05-20 18:34:07 +0200372 typename V = decltype(MakeVal(std::declval<U>())),
373 absl::enable_if_t<std::is_arithmetic<U>::value ||
374 std::is_enum<U>::value>* = nullptr>
375 RTC_FORCE_INLINE LogStreamer<V> operator<<(U arg) const {
376 return LogStreamer<V>(MakeVal(arg), this);
Karl Wibergcefc4652018-05-23 23:20:38 +0200377 }
378
Amit Hilbuch10c5a932019-03-18 13:09:18 -0700379 template <typename U,
Sebastian Janssonf4e085a2019-05-20 18:34:07 +0200380 typename V = decltype(MakeVal(std::declval<U>())),
381 absl::enable_if_t<!std::is_arithmetic<U>::value &&
382 !std::is_enum<U>::value>* = nullptr>
383 RTC_FORCE_INLINE LogStreamer<V> operator<<(const U& arg) const {
384 return LogStreamer<V>(MakeVal(arg), this);
Karl Wibergcefc4652018-05-23 23:20:38 +0200385 }
386
387 template <typename... Us>
388 RTC_FORCE_INLINE static void Call(const Us&... args) {
389 static constexpr LogArgType t[] = {Us::Type()..., LogArgType::kEnd};
390 Log(t, args.GetVal()...);
391 }
392};
393
394// Inductive case: We've already seen at least one << argument. The most recent
395// one had type `T`, and the earlier ones had types `Ts`.
396template <typename T, typename... Ts>
397class LogStreamer<T, Ts...> final {
398 public:
399 RTC_FORCE_INLINE LogStreamer(T arg, const LogStreamer<Ts...>* prior)
400 : arg_(arg), prior_(prior) {}
401
Amit Hilbuch10c5a932019-03-18 13:09:18 -0700402 template <typename U,
Sebastian Janssonf4e085a2019-05-20 18:34:07 +0200403 typename V = decltype(MakeVal(std::declval<U>())),
404 absl::enable_if_t<std::is_arithmetic<U>::value ||
405 std::is_enum<U>::value>* = nullptr>
406 RTC_FORCE_INLINE LogStreamer<V, T, Ts...> operator<<(U arg) const {
407 return LogStreamer<V, T, Ts...>(MakeVal(arg), this);
Karl Wibergcefc4652018-05-23 23:20:38 +0200408 }
409
Amit Hilbuch10c5a932019-03-18 13:09:18 -0700410 template <typename U,
Sebastian Janssonf4e085a2019-05-20 18:34:07 +0200411 typename V = decltype(MakeVal(std::declval<U>())),
412 absl::enable_if_t<!std::is_arithmetic<U>::value &&
413 !std::is_enum<U>::value>* = nullptr>
414 RTC_FORCE_INLINE LogStreamer<V, T, Ts...> operator<<(const U& arg) const {
415 return LogStreamer<V, T, Ts...>(MakeVal(arg), this);
Karl Wibergcefc4652018-05-23 23:20:38 +0200416 }
417
418 template <typename... Us>
419 RTC_FORCE_INLINE void Call(const Us&... args) const {
420 prior_->Call(arg_, args...);
421 }
422
423 private:
424 // The most recent argument.
425 T arg_;
426
427 // Earlier arguments.
428 const LogStreamer<Ts...>* prior_;
429};
430
431class LogCall final {
432 public:
433 // This can be any binary operator with precedence lower than <<.
Artem Titov6a4a1462019-11-26 16:24:46 +0100434 // We return bool here to be able properly remove logging if
435 // RTC_DISABLE_LOGGING is defined.
Karl Wibergcefc4652018-05-23 23:20:38 +0200436 template <typename... Ts>
Artem Titov6a4a1462019-11-26 16:24:46 +0100437 RTC_FORCE_INLINE bool operator&(const LogStreamer<Ts...>& streamer) {
Karl Wibergcefc4652018-05-23 23:20:38 +0200438 streamer.Call();
Artem Titov6a4a1462019-11-26 16:24:46 +0100439 return true;
Karl Wibergcefc4652018-05-23 23:20:38 +0200440 }
441};
442
Mirko Bonadeif1df04b2020-03-23 19:53:23 +0100443// This class is used to explicitly ignore values in the conditional
444// logging macros. This avoids compiler warnings like "value computed
445// is not used" and "statement has no effect".
446class LogMessageVoidify {
447 public:
448 LogMessageVoidify() = default;
449 // This has to be an operator with a precedence lower than << but
450 // higher than ?:
451 template <typename... Ts>
452 void operator&(LogStreamer<Ts...>&& streamer) {}
453};
454
Karl Wibergcefc4652018-05-23 23:20:38 +0200455} // namespace webrtc_logging_impl
456
457// Direct use of this class is deprecated; please use the logging macros
458// instead.
459// TODO(bugs.webrtc.org/9278): Move this class to an unnamed namespace in the
460// .cc file.
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200461class LogMessage {
462 public:
Karl Wiberg1ffb3742018-05-04 15:04:48 +0200463 // Same as the above, but using a compile-time constant for the logging
464 // severity. This saves space at the call site, since passing an empty struct
465 // is generally the same as not passing an argument at all.
466 template <LoggingSeverity S>
467 RTC_NO_INLINE LogMessage(const char* file,
468 int line,
469 std::integral_constant<LoggingSeverity, S>)
470 : LogMessage(file, line, S) {}
471
Artem Titov6a4a1462019-11-26 16:24:46 +0100472#if RTC_LOG_ENABLED()
473 LogMessage(const char* file, int line, LoggingSeverity sev);
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200474 LogMessage(const char* file,
475 int line,
476 LoggingSeverity sev,
Karl Wibergab4f1c12018-05-04 10:42:28 +0200477 LogErrorContext err_ctx,
478 int err);
Tommie51a0a82018-02-27 15:30:29 +0100479#if defined(WEBRTC_ANDROID)
480 LogMessage(const char* file, int line, LoggingSeverity sev, const char* tag);
481#endif
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200482 ~LogMessage();
483
Byoungchan Lee14af7622022-01-12 05:24:58 +0900484 LogMessage(const LogMessage&) = delete;
485 LogMessage& operator=(const LogMessage&) = delete;
486
Karl Wibergcefc4652018-05-23 23:20:38 +0200487 void AddTag(const char* tag);
Jonas Olssond8c50782018-09-07 11:21:28 +0200488 rtc::StringBuilder& stream();
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200489 // Returns the time at which this function was called for the first time.
490 // The time will be used as the logging start time.
491 // If this is not called externally, the LogMessage ctor also calls it, in
492 // which case the logging start time will be the time of the first LogMessage
493 // instance is created.
494 static int64_t LogStartTime();
Artem Titov96e3b992021-07-26 16:03:14 +0200495 // Returns the wall clock equivalent of `LogStartTime`, in seconds from the
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200496 // epoch.
497 static uint32_t WallClockStartTime();
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200498 // LogThreads: Display the thread identifier of the current thread
499 static void LogThreads(bool on = true);
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200500 // LogTimestamps: Display the elapsed time of the program
501 static void LogTimestamps(bool on = true);
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200502 // These are the available logging channels
503 // Debug: Debug console on Windows, otherwise stderr
504 static void LogToDebug(LoggingSeverity min_sev);
Jonas Olsson2b6f1352018-02-15 11:57:03 +0100505 static LoggingSeverity GetLogToDebug();
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200506 // Sets whether logs will be directed to stderr in debug mode.
507 static void SetLogToStderr(bool log_to_stderr);
Danil Chapovalovb9f69022019-10-21 09:19:10 +0200508 // Stream: Any non-blocking stream interface.
Artem Titov96e3b992021-07-26 16:03:14 +0200509 // Installs the `stream` to collect logs with severtiy `min_sev` or higher.
510 // `stream` must live until deinstalled by RemoveLogToStream.
511 // If `stream` is the first stream added to the system, we might miss some
Markus Handell531bd0f2020-07-08 10:58:19 +0200512 // early concurrent log statement happening from another thread happening near
513 // this instant.
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200514 static void AddLogToStream(LogSink* stream, LoggingSeverity min_sev);
Markus Handell531bd0f2020-07-08 10:58:19 +0200515 // Removes the specified stream, without destroying it. When the method
Artem Titov96e3b992021-07-26 16:03:14 +0200516 // has completed, it's guaranteed that `stream` will receive no more logging
Markus Handell531bd0f2020-07-08 10:58:19 +0200517 // calls.
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200518 static void RemoveLogToStream(LogSink* stream);
Danil Chapovalovb9f69022019-10-21 09:19:10 +0200519 // Returns the severity for the specified stream, of if none is specified,
520 // the minimum stream severity.
521 static int GetLogToStream(LogSink* stream = nullptr);
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200522 // Testing against MinLogSeverity allows code to avoid potentially expensive
523 // logging operations by pre-checking the logging level.
Jonas Olsson2b6f1352018-02-15 11:57:03 +0100524 static int GetMinLogSeverity();
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200525 // Parses the provided parameter stream to configure the options above.
526 // Useful for configuring logging from the command line.
Ali Tofigh2ab914c2022-04-13 12:55:15 +0200527 static void ConfigureLogging(absl::string_view params);
Artem Titov96e3b992021-07-26 16:03:14 +0200528 // Checks the current global debug severity and if the `streams_` collection
529 // is empty. If `severity` is smaller than the global severity and if the
530 // `streams_` collection is empty, the LogMessage will be considered a noop
Jonas Olssond8c50782018-09-07 11:21:28 +0200531 // LogMessage.
532 static bool IsNoop(LoggingSeverity severity);
Karl Wibergdd7df5c2020-09-22 11:07:53 +0200533 // Version of IsNoop that uses fewer instructions at the call site, since the
534 // caller doesn't have to pass an argument.
535 template <LoggingSeverity S>
536 RTC_NO_INLINE static bool IsNoop() {
537 return IsNoop(S);
538 }
Artem Titov6a4a1462019-11-26 16:24:46 +0100539#else
540 // Next methods do nothing; no one will call these functions.
541 LogMessage(const char* file, int line, LoggingSeverity sev) {}
542 LogMessage(const char* file,
543 int line,
544 LoggingSeverity sev,
545 LogErrorContext err_ctx,
546 int err) {}
547#if defined(WEBRTC_ANDROID)
548 LogMessage(const char* file, int line, LoggingSeverity sev, const char* tag) {
549 }
550#endif
Artem Titov6a4a1462019-11-26 16:24:46 +0100551 ~LogMessage() = default;
552
553 inline void AddTag(const char* tag) {}
554 inline rtc::StringBuilder& stream() { return print_stream_; }
555 inline static int64_t LogStartTime() { return 0; }
556 inline static uint32_t WallClockStartTime() { return 0; }
557 inline static void LogThreads(bool on = true) {}
558 inline static void LogTimestamps(bool on = true) {}
559 inline static void LogToDebug(LoggingSeverity min_sev) {}
560 inline static LoggingSeverity GetLogToDebug() {
561 return LoggingSeverity::LS_INFO;
562 }
563 inline static void SetLogToStderr(bool log_to_stderr) {}
564 inline static void AddLogToStream(LogSink* stream, LoggingSeverity min_sev) {}
565 inline static void RemoveLogToStream(LogSink* stream) {}
566 inline static int GetLogToStream(LogSink* stream = nullptr) { return 0; }
567 inline static int GetMinLogSeverity() { return 0; }
Ali Tofigh2ab914c2022-04-13 12:55:15 +0200568 inline static void ConfigureLogging(absl::string_view params) {}
Karl Wiberg0e884382020-09-22 09:34:45 +0200569 static constexpr bool IsNoop(LoggingSeverity severity) { return true; }
Karl Wibergdd7df5c2020-09-22 11:07:53 +0200570 template <LoggingSeverity S>
571 static constexpr bool IsNoop() {
572 return IsNoop(S);
573 }
Artem Titov6a4a1462019-11-26 16:24:46 +0100574#endif // RTC_LOG_ENABLED()
Jonas Olssond8c50782018-09-07 11:21:28 +0200575
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200576 private:
Tommifef05002018-02-27 13:51:08 +0100577 friend class LogMessageForTesting;
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200578
Artem Titov6a4a1462019-11-26 16:24:46 +0100579#if RTC_LOG_ENABLED()
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200580 // Updates min_sev_ appropriately when debug sinks change.
581 static void UpdateMinLogSeverity();
582
Mirko Bonadei96191f82022-08-03 08:12:33 +0000583 // This writes out the actual log messages.
584 static void OutputToDebug(const LogLineRef& log_line_ref);
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200585
Tommifef05002018-02-27 13:51:08 +0100586 // Called from the dtor (or from a test) to append optional extra error
587 // information to the log stream and a newline character.
588 void FinishPrintStream();
589
Mirko Bonadei96191f82022-08-03 08:12:33 +0000590 LogLineRef log_line_;
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200591
592 // String data generated in the constructor, that should be appended to
593 // the message before output.
594 std::string extra_;
595
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200596 // The output streams and their associated severities
Danil Chapovalovb9f69022019-10-21 09:19:10 +0200597 static LogSink* streams_;
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200598
Artem Titov96e3b992021-07-26 16:03:14 +0200599 // Holds true with high probability if `streams_` is empty, false with high
Markus Handellce1ff6f2020-07-08 08:52:48 +0200600 // probability otherwise. Operated on with std::memory_order_relaxed because
Markus Handell531bd0f2020-07-08 10:58:19 +0200601 // it's ok to lose or log some additional statements near the instant streams
Markus Handellce1ff6f2020-07-08 08:52:48 +0200602 // are added/removed.
603 static std::atomic<bool> streams_empty_;
604
Mirko Bonadei96191f82022-08-03 08:12:33 +0000605 // Flags for formatting options and their potential values.
606 static bool log_thread_;
607 static bool log_timestamp_;
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200608
609 // Determines if logs will be directed to stderr in debug mode.
610 static bool log_to_stderr_;
Artem Titov6a4a1462019-11-26 16:24:46 +0100611#else // RTC_LOG_ENABLED()
612 // Next methods do nothing; no one will call these functions.
613 inline static void UpdateMinLogSeverity() {}
614#if defined(WEBRTC_ANDROID)
Mirko Bonadei96191f82022-08-03 08:12:33 +0000615 inline static void OutputToDebug(absl::string_view filename,
616 int line,
617 absl::string_view msg,
Artem Titov6a4a1462019-11-26 16:24:46 +0100618 LoggingSeverity severity,
619 const char* tag) {}
620#else
Mirko Bonadei96191f82022-08-03 08:12:33 +0000621 inline static void OutputToDebug(absl::string_view filename,
622 int line,
623 absl::string_view msg,
Artem Titov6a4a1462019-11-26 16:24:46 +0100624 LoggingSeverity severity) {}
625#endif // defined(WEBRTC_ANDROID)
626 inline void FinishPrintStream() {}
627#endif // RTC_LOG_ENABLED()
628
629 // The stringbuilder that buffers the formatted message before output
630 rtc::StringBuilder print_stream_;
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200631};
632
633//////////////////////////////////////////////////////////////////////
634// Logging Helpers
635//////////////////////////////////////////////////////////////////////
636
Karl Wibergdd7df5c2020-09-22 11:07:53 +0200637#define RTC_LOG_FILE_LINE(sev, file, line) \
638 ::rtc::webrtc_logging_impl::LogCall() & \
639 ::rtc::webrtc_logging_impl::LogStreamer<>() \
640 << ::rtc::webrtc_logging_impl::LogMetadata(file, line, sev)
Jonas Olsson8a7916b2018-09-06 09:50:23 +0200641
Karl Wibergdd7df5c2020-09-22 11:07:53 +0200642#define RTC_LOG(sev) \
643 !rtc::LogMessage::IsNoop<::rtc::sev>() && \
644 RTC_LOG_FILE_LINE(::rtc::sev, __FILE__, __LINE__)
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200645
Karl Wibergcefc4652018-05-23 23:20:38 +0200646// The _V version is for when a variable is passed in.
Karl Wibergdd7df5c2020-09-22 11:07:53 +0200647#define RTC_LOG_V(sev) \
648 !rtc::LogMessage::IsNoop(sev) && RTC_LOG_FILE_LINE(sev, __FILE__, __LINE__)
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200649
650// The _F version prefixes the message with the current function name.
651#if (defined(__GNUC__) && !defined(NDEBUG)) || defined(WANT_PRETTY_LOG_F)
Mirko Bonadei8ed8e562017-10-27 09:43:53 +0200652#define RTC_LOG_F(sev) RTC_LOG(sev) << __PRETTY_FUNCTION__ << ": "
Yves Gerey665174f2018-06-19 15:03:05 +0200653#define RTC_LOG_T_F(sev) \
654 RTC_LOG(sev) << this << ": " << __PRETTY_FUNCTION__ << ": "
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200655#else
Mirko Bonadei8ed8e562017-10-27 09:43:53 +0200656#define RTC_LOG_F(sev) RTC_LOG(sev) << __FUNCTION__ << ": "
Patrik Höglundc2962552017-11-17 13:40:22 +0000657#define RTC_LOG_T_F(sev) RTC_LOG(sev) << this << ": " << __FUNCTION__ << ": "
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200658#endif
659
Jiawei Ou14e5f0b2020-03-04 13:38:02 -0800660#define RTC_LOG_CHECK_LEVEL(sev) ::rtc::LogCheckLevel(::rtc::sev)
661#define RTC_LOG_CHECK_LEVEL_V(sev) ::rtc::LogCheckLevel(sev)
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200662
663inline bool LogCheckLevel(LoggingSeverity sev) {
664 return (LogMessage::GetMinLogSeverity() <= sev);
665}
666
Karl Wiberg92e37962020-09-22 13:22:20 +0200667#define RTC_LOG_E(sev, ctx, err) \
668 !rtc::LogMessage::IsNoop<::rtc::sev>() && \
669 ::rtc::webrtc_logging_impl::LogCall() & \
670 ::rtc::webrtc_logging_impl::LogStreamer<>() \
671 << ::rtc::webrtc_logging_impl::LogMetadataErr { \
672 {__FILE__, __LINE__, ::rtc::sev}, ::rtc::ERRCTX_##ctx, (err) \
Jonas Olssona4d87372019-07-05 19:08:33 +0200673 }
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200674
Mirko Bonadei8ed8e562017-10-27 09:43:53 +0200675#define RTC_LOG_T(sev) RTC_LOG(sev) << this << ": "
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200676
Yves Gerey665174f2018-06-19 15:03:05 +0200677#define RTC_LOG_ERRNO_EX(sev, err) RTC_LOG_E(sev, ERRNO, err)
678#define RTC_LOG_ERRNO(sev) RTC_LOG_ERRNO_EX(sev, errno)
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200679
680#if defined(WEBRTC_WIN)
Yves Gerey665174f2018-06-19 15:03:05 +0200681#define RTC_LOG_GLE_EX(sev, err) RTC_LOG_E(sev, HRESULT, err)
Karl Wibergcefc4652018-05-23 23:20:38 +0200682#define RTC_LOG_GLE(sev) RTC_LOG_GLE_EX(sev, static_cast<int>(GetLastError()))
Yves Gerey665174f2018-06-19 15:03:05 +0200683#define RTC_LOG_ERR_EX(sev, err) RTC_LOG_GLE_EX(sev, err)
684#define RTC_LOG_ERR(sev) RTC_LOG_GLE(sev)
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200685#elif defined(__native_client__) && __native_client__
Yves Gerey665174f2018-06-19 15:03:05 +0200686#define RTC_LOG_ERR_EX(sev, err) RTC_LOG(sev)
687#define RTC_LOG_ERR(sev) RTC_LOG(sev)
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200688#elif defined(WEBRTC_POSIX)
Yves Gerey665174f2018-06-19 15:03:05 +0200689#define RTC_LOG_ERR_EX(sev, err) RTC_LOG_ERRNO_EX(sev, err)
690#define RTC_LOG_ERR(sev) RTC_LOG_ERRNO(sev)
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200691#endif // WEBRTC_WIN
692
Karl Wibergcefc4652018-05-23 23:20:38 +0200693#ifdef WEBRTC_ANDROID
694
695namespace webrtc_logging_impl {
696// TODO(kwiberg): Replace these with absl::string_view.
Yves Gerey665174f2018-06-19 15:03:05 +0200697inline const char* AdaptString(const char* str) {
698 return str;
699}
700inline const char* AdaptString(const std::string& str) {
701 return str.c_str();
702}
Karl Wibergcefc4652018-05-23 23:20:38 +0200703} // namespace webrtc_logging_impl
704
Karl Wiberg92e37962020-09-22 13:22:20 +0200705#define RTC_LOG_TAG(sev, tag) \
706 !rtc::LogMessage::IsNoop(sev) && \
707 ::rtc::webrtc_logging_impl::LogCall() & \
708 ::rtc::webrtc_logging_impl::LogStreamer<>() \
709 << ::rtc::webrtc_logging_impl::LogMetadataTag { \
710 sev, ::rtc::webrtc_logging_impl::AdaptString(tag) \
Jonas Olssona4d87372019-07-05 19:08:33 +0200711 }
Karl Wibergcefc4652018-05-23 23:20:38 +0200712
Tommie51a0a82018-02-27 15:30:29 +0100713#else
Karl Wibergcefc4652018-05-23 23:20:38 +0200714
Tommie51a0a82018-02-27 15:30:29 +0100715// DEPRECATED. This macro is only intended for Android.
Karl Wibergcefc4652018-05-23 23:20:38 +0200716#define RTC_LOG_TAG(sev, tag) RTC_LOG_V(sev)
717
Tommie51a0a82018-02-27 15:30:29 +0100718#endif
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200719
Fredrik Solenbergb3d7cac2017-11-17 15:22:37 +0100720// The RTC_DLOG macros are equivalent to their RTC_LOG counterparts except that
721// they only generate code in debug builds.
722#if RTC_DLOG_IS_ON
723#define RTC_DLOG(sev) RTC_LOG(sev)
724#define RTC_DLOG_V(sev) RTC_LOG_V(sev)
725#define RTC_DLOG_F(sev) RTC_LOG_F(sev)
726#else
Mirko Bonadeif1df04b2020-03-23 19:53:23 +0100727#define RTC_DLOG_EAT_STREAM_PARAMS() \
728 while (false) \
729 ::rtc::webrtc_logging_impl::LogMessageVoidify() & \
730 (::rtc::webrtc_logging_impl::LogStreamer<>())
Karl Wibergcefc4652018-05-23 23:20:38 +0200731#define RTC_DLOG(sev) RTC_DLOG_EAT_STREAM_PARAMS()
732#define RTC_DLOG_V(sev) RTC_DLOG_EAT_STREAM_PARAMS()
733#define RTC_DLOG_F(sev) RTC_DLOG_EAT_STREAM_PARAMS()
Fredrik Solenbergb3d7cac2017-11-17 15:22:37 +0100734#endif
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200735
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200736} // namespace rtc
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000737
Mirko Bonadei92ea95e2017-09-15 06:47:31 +0200738#endif // RTC_BASE_LOGGING_H_