blob: 2c3a6dcb22243d48e104fddac9871a08d821d7fa [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:
Mirko Bonadei73f0c212022-08-03 13:18:30 +0000114 absl::string_view message() const { return message_; }
115 absl::string_view filename() const { return filename_; }
116 int line() const { return line_; }
117 absl::optional<PlatformThreadId> thread_id() const { return thread_id_; }
118 webrtc::Timestamp timestamp() const { return timestamp_; }
119 absl::string_view tag() const { return tag_; }
Mirko Bonadei96191f82022-08-03 08:12:33 +0000120 LoggingSeverity severity() const { return severity_; }
121
Mirko Bonadei821b92a2022-08-03 15:04:48 +0000122#if RTC_LOG_ENABLED()
Mirko Bonadei96191f82022-08-03 08:12:33 +0000123 std::string DefaultLogLine() const;
Mirko Bonadei821b92a2022-08-03 15:04:48 +0000124#else
125 std::string DefaultLogLine() const { return ""; }
126#endif
Mirko Bonadei96191f82022-08-03 08:12:33 +0000127
128 private:
129 friend class LogMessage;
130 void set_message(std::string message) { message_ = std::move(message); }
131 void set_filename(absl::string_view filename) { filename_ = filename; }
132 void set_line(int line) { line_ = line; }
133 void set_thread_id(absl::optional<PlatformThreadId> thread_id) {
134 thread_id_ = thread_id;
135 }
136 void set_timestamp(webrtc::Timestamp timestamp) { timestamp_ = timestamp; }
137 void set_tag(absl::string_view tag) { tag_ = tag; }
138 void set_severity(LoggingSeverity severity) { severity_ = severity; }
139
140 std::string message_;
141 absl::string_view filename_;
142 int line_ = 0;
143 absl::optional<PlatformThreadId> thread_id_;
144 webrtc::Timestamp timestamp_ = webrtc::Timestamp::MinusInfinity();
145 // The default Android debug output tag.
146 absl::string_view tag_ = "libjingle";
147 // The severity level of this message
148 LoggingSeverity severity_;
149};
150
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200151// Virtual sink interface that can receive log messages.
152class LogSink {
153 public:
154 LogSink() {}
155 virtual ~LogSink() {}
Paulina Hensmanf1e3cb42018-06-20 14:07:05 +0200156 virtual void OnLogMessage(const std::string& msg,
157 LoggingSeverity severity,
158 const char* tag);
Jiawei Ou3ea18782018-10-31 23:14:24 -0700159 virtual void OnLogMessage(const std::string& message,
160 LoggingSeverity severity);
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200161 virtual void OnLogMessage(const std::string& message) = 0;
Danil Chapovalovb9f69022019-10-21 09:19:10 +0200162
Ali Tofigh6364d082022-03-14 13:32:04 +0100163 virtual void OnLogMessage(absl::string_view msg,
164 LoggingSeverity severity,
165 const char* tag);
166 virtual void OnLogMessage(absl::string_view message,
167 LoggingSeverity severity);
168 virtual void OnLogMessage(absl::string_view message);
Mirko Bonadei96191f82022-08-03 08:12:33 +0000169 virtual void OnLogMessage(const LogLineRef& line);
Ali Tofigh6364d082022-03-14 13:32:04 +0100170
Danil Chapovalovb9f69022019-10-21 09:19:10 +0200171 private:
172 friend class ::rtc::LogMessage;
Artem Titov6a4a1462019-11-26 16:24:46 +0100173#if RTC_LOG_ENABLED()
Danil Chapovalovb9f69022019-10-21 09:19:10 +0200174 // Members for LogMessage class to keep linked list of the registered sinks.
175 LogSink* next_ = nullptr;
176 LoggingSeverity min_severity_;
Artem Titov6a4a1462019-11-26 16:24:46 +0100177#endif
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200178};
179
Karl Wibergcefc4652018-05-23 23:20:38 +0200180namespace webrtc_logging_impl {
181
182class LogMetadata {
183 public:
184 LogMetadata(const char* file, int line, LoggingSeverity severity)
185 : file_(file),
186 line_and_sev_(static_cast<uint32_t>(line) << 3 | severity) {}
187 LogMetadata() = default;
188
189 const char* File() const { return file_; }
190 int Line() const { return line_and_sev_ >> 3; }
191 LoggingSeverity Severity() const {
192 return static_cast<LoggingSeverity>(line_and_sev_ & 0x7);
193 }
194
195 private:
196 const char* file_;
197
198 // Line number and severity, the former in the most significant 29 bits, the
199 // latter in the least significant 3 bits. (This is an optimization; since
200 // both numbers are usually compile-time constants, this way we can load them
201 // both with a single instruction.)
202 uint32_t line_and_sev_;
203};
204static_assert(std::is_trivial<LogMetadata>::value, "");
205
206struct LogMetadataErr {
207 LogMetadata meta;
208 LogErrorContext err_ctx;
209 int err;
210};
211
212#ifdef WEBRTC_ANDROID
213struct LogMetadataTag {
214 LoggingSeverity severity;
215 const char* tag;
216};
217#endif
218
219enum class LogArgType : int8_t {
220 kEnd = 0,
221 kInt,
222 kLong,
223 kLongLong,
224 kUInt,
225 kULong,
226 kULongLong,
227 kDouble,
228 kLongDouble,
229 kCharP,
230 kStdString,
Jonas Olssonf2ce37c2018-09-12 15:32:47 +0200231 kStringView,
Karl Wibergcefc4652018-05-23 23:20:38 +0200232 kVoidP,
233 kLogMetadata,
234 kLogMetadataErr,
235#ifdef WEBRTC_ANDROID
236 kLogMetadataTag,
237#endif
238};
239
240// Wrapper for log arguments. Only ever make values of this type with the
241// MakeVal() functions.
242template <LogArgType N, typename T>
243struct Val {
244 static constexpr LogArgType Type() { return N; }
245 T GetVal() const { return val; }
246 T val;
247};
248
Sebastian Janssonb1138622019-04-11 16:48:15 +0200249// Case for when we need to construct a temp string and then print that.
250// (We can't use Val<CheckArgType::kStdString, const std::string*>
251// because we need somewhere to store the temp string.)
252struct ToStringVal {
Karl Wibergcefc4652018-05-23 23:20:38 +0200253 static constexpr LogArgType Type() { return LogArgType::kStdString; }
254 const std::string* GetVal() const { return &val; }
255 std::string val;
256};
257
258inline Val<LogArgType::kInt, int> MakeVal(int x) {
259 return {x};
260}
261inline Val<LogArgType::kLong, long> MakeVal(long x) {
262 return {x};
263}
264inline Val<LogArgType::kLongLong, long long> MakeVal(long long x) {
265 return {x};
266}
267inline Val<LogArgType::kUInt, unsigned int> MakeVal(unsigned int x) {
268 return {x};
269}
270inline Val<LogArgType::kULong, unsigned long> MakeVal(unsigned long x) {
271 return {x};
272}
273inline Val<LogArgType::kULongLong, unsigned long long> MakeVal(
274 unsigned long long x) {
275 return {x};
276}
277
278inline Val<LogArgType::kDouble, double> MakeVal(double x) {
279 return {x};
280}
281inline Val<LogArgType::kLongDouble, long double> MakeVal(long double x) {
282 return {x};
283}
284
285inline Val<LogArgType::kCharP, const char*> MakeVal(const char* x) {
286 return {x};
287}
288inline Val<LogArgType::kStdString, const std::string*> MakeVal(
289 const std::string& x) {
290 return {&x};
291}
Jonas Olssonf2ce37c2018-09-12 15:32:47 +0200292inline Val<LogArgType::kStringView, const absl::string_view*> MakeVal(
293 const absl::string_view& x) {
294 return {&x};
295}
Karl Wibergcefc4652018-05-23 23:20:38 +0200296
297inline Val<LogArgType::kVoidP, const void*> MakeVal(const void* x) {
298 return {x};
299}
300
301inline Val<LogArgType::kLogMetadata, LogMetadata> MakeVal(
302 const LogMetadata& x) {
303 return {x};
304}
305inline Val<LogArgType::kLogMetadataErr, LogMetadataErr> MakeVal(
306 const LogMetadataErr& x) {
307 return {x};
308}
309
Amit Hilbuch10c5a932019-03-18 13:09:18 -0700310// The enum class types are not implicitly convertible to arithmetic types.
Sebastian Janssonf4e085a2019-05-20 18:34:07 +0200311template <typename T,
312 absl::enable_if_t<std::is_enum<T>::value &&
313 !std::is_arithmetic<T>::value>* = nullptr>
314inline decltype(MakeVal(std::declval<absl::underlying_type_t<T>>())) MakeVal(
315 T x) {
316 return {static_cast<absl::underlying_type_t<T>>(x)};
Amit Hilbuch10c5a932019-03-18 13:09:18 -0700317}
318
Karl Wibergcefc4652018-05-23 23:20:38 +0200319#ifdef WEBRTC_ANDROID
320inline Val<LogArgType::kLogMetadataTag, LogMetadataTag> MakeVal(
321 const LogMetadataTag& x) {
322 return {x};
323}
324#endif
325
Sebastian Janssonf4e085a2019-05-20 18:34:07 +0200326template <typename T, class = void>
Sebastian Janssonb1138622019-04-11 16:48:15 +0200327struct has_to_log_string : std::false_type {};
328template <typename T>
Evan Shrubsole7765f9e2022-04-25 11:04:12 +0200329struct has_to_log_string<T,
330 absl::enable_if_t<std::is_convertible<
331 decltype(ToLogString(std::declval<T>())),
332 std::string>::value>> : std::true_type {};
333
334template <typename T, absl::enable_if_t<has_to_log_string<T>::value>* = nullptr>
335ToStringVal MakeVal(const T& x) {
336 return {ToLogString(x)};
337}
Sebastian Janssonb1138622019-04-11 16:48:15 +0200338
Karl Wibergcefc4652018-05-23 23:20:38 +0200339// Handle arbitrary types other than the above by falling back to stringstream.
340// TODO(bugs.webrtc.org/9278): Get rid of this overload when callers don't need
341// it anymore. No in-tree caller does, but some external callers still do.
342template <
343 typename T,
Sebastian Janssonf4e085a2019-05-20 18:34:07 +0200344 typename T1 = absl::decay_t<T>,
345 absl::enable_if_t<std::is_class<T1>::value &&
346 !std::is_same<T1, std::string>::value &&
347 !std::is_same<T1, LogMetadata>::value &&
348 !has_to_log_string<T1>::value &&
Karl Wibergcefc4652018-05-23 23:20:38 +0200349#ifdef WEBRTC_ANDROID
Sebastian Janssonf4e085a2019-05-20 18:34:07 +0200350 !std::is_same<T1, LogMetadataTag>::value &&
Karl Wibergcefc4652018-05-23 23:20:38 +0200351#endif
Sebastian Janssonf4e085a2019-05-20 18:34:07 +0200352 !std::is_same<T1, LogMetadataErr>::value>* = nullptr>
Sebastian Janssonb1138622019-04-11 16:48:15 +0200353ToStringVal MakeVal(const T& x) {
Karl Wibergcefc4652018-05-23 23:20:38 +0200354 std::ostringstream os; // no-presubmit-check TODO(webrtc:8982)
355 os << x;
356 return {os.str()};
357}
358
Artem Titov6a4a1462019-11-26 16:24:46 +0100359#if RTC_LOG_ENABLED()
Karl Wibergcefc4652018-05-23 23:20:38 +0200360void Log(const LogArgType* fmt, ...);
Artem Titov6a4a1462019-11-26 16:24:46 +0100361#else
362inline void Log(const LogArgType* fmt, ...) {
363 // Do nothing, shouldn't be invoked
364}
365#endif
Karl Wibergcefc4652018-05-23 23:20:38 +0200366
367// Ephemeral type that represents the result of the logging << operator.
368template <typename... Ts>
369class LogStreamer;
370
371// Base case: Before the first << argument.
372template <>
373class LogStreamer<> final {
374 public:
Amit Hilbuch10c5a932019-03-18 13:09:18 -0700375 template <typename U,
Sebastian Janssonf4e085a2019-05-20 18:34:07 +0200376 typename V = decltype(MakeVal(std::declval<U>())),
377 absl::enable_if_t<std::is_arithmetic<U>::value ||
378 std::is_enum<U>::value>* = nullptr>
379 RTC_FORCE_INLINE LogStreamer<V> operator<<(U arg) const {
380 return LogStreamer<V>(MakeVal(arg), this);
Karl Wibergcefc4652018-05-23 23:20:38 +0200381 }
382
Amit Hilbuch10c5a932019-03-18 13:09:18 -0700383 template <typename U,
Sebastian Janssonf4e085a2019-05-20 18:34:07 +0200384 typename V = decltype(MakeVal(std::declval<U>())),
385 absl::enable_if_t<!std::is_arithmetic<U>::value &&
386 !std::is_enum<U>::value>* = nullptr>
387 RTC_FORCE_INLINE LogStreamer<V> operator<<(const U& arg) const {
388 return LogStreamer<V>(MakeVal(arg), this);
Karl Wibergcefc4652018-05-23 23:20:38 +0200389 }
390
391 template <typename... Us>
392 RTC_FORCE_INLINE static void Call(const Us&... args) {
393 static constexpr LogArgType t[] = {Us::Type()..., LogArgType::kEnd};
394 Log(t, args.GetVal()...);
395 }
396};
397
398// Inductive case: We've already seen at least one << argument. The most recent
399// one had type `T`, and the earlier ones had types `Ts`.
400template <typename T, typename... Ts>
401class LogStreamer<T, Ts...> final {
402 public:
403 RTC_FORCE_INLINE LogStreamer(T arg, const LogStreamer<Ts...>* prior)
404 : arg_(arg), prior_(prior) {}
405
Amit Hilbuch10c5a932019-03-18 13:09:18 -0700406 template <typename U,
Sebastian Janssonf4e085a2019-05-20 18:34:07 +0200407 typename V = decltype(MakeVal(std::declval<U>())),
408 absl::enable_if_t<std::is_arithmetic<U>::value ||
409 std::is_enum<U>::value>* = nullptr>
410 RTC_FORCE_INLINE LogStreamer<V, T, Ts...> operator<<(U arg) const {
411 return LogStreamer<V, T, Ts...>(MakeVal(arg), this);
Karl Wibergcefc4652018-05-23 23:20:38 +0200412 }
413
Amit Hilbuch10c5a932019-03-18 13:09:18 -0700414 template <typename U,
Sebastian Janssonf4e085a2019-05-20 18:34:07 +0200415 typename V = decltype(MakeVal(std::declval<U>())),
416 absl::enable_if_t<!std::is_arithmetic<U>::value &&
417 !std::is_enum<U>::value>* = nullptr>
418 RTC_FORCE_INLINE LogStreamer<V, T, Ts...> operator<<(const U& arg) const {
419 return LogStreamer<V, T, Ts...>(MakeVal(arg), this);
Karl Wibergcefc4652018-05-23 23:20:38 +0200420 }
421
422 template <typename... Us>
423 RTC_FORCE_INLINE void Call(const Us&... args) const {
424 prior_->Call(arg_, args...);
425 }
426
427 private:
428 // The most recent argument.
429 T arg_;
430
431 // Earlier arguments.
432 const LogStreamer<Ts...>* prior_;
433};
434
435class LogCall final {
436 public:
437 // This can be any binary operator with precedence lower than <<.
Artem Titov6a4a1462019-11-26 16:24:46 +0100438 // We return bool here to be able properly remove logging if
439 // RTC_DISABLE_LOGGING is defined.
Karl Wibergcefc4652018-05-23 23:20:38 +0200440 template <typename... Ts>
Artem Titov6a4a1462019-11-26 16:24:46 +0100441 RTC_FORCE_INLINE bool operator&(const LogStreamer<Ts...>& streamer) {
Karl Wibergcefc4652018-05-23 23:20:38 +0200442 streamer.Call();
Artem Titov6a4a1462019-11-26 16:24:46 +0100443 return true;
Karl Wibergcefc4652018-05-23 23:20:38 +0200444 }
445};
446
Mirko Bonadeif1df04b2020-03-23 19:53:23 +0100447// This class is used to explicitly ignore values in the conditional
448// logging macros. This avoids compiler warnings like "value computed
449// is not used" and "statement has no effect".
450class LogMessageVoidify {
451 public:
452 LogMessageVoidify() = default;
453 // This has to be an operator with a precedence lower than << but
454 // higher than ?:
455 template <typename... Ts>
456 void operator&(LogStreamer<Ts...>&& streamer) {}
457};
458
Karl Wibergcefc4652018-05-23 23:20:38 +0200459} // namespace webrtc_logging_impl
460
461// Direct use of this class is deprecated; please use the logging macros
462// instead.
463// TODO(bugs.webrtc.org/9278): Move this class to an unnamed namespace in the
464// .cc file.
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200465class LogMessage {
466 public:
Karl Wiberg1ffb3742018-05-04 15:04:48 +0200467 // Same as the above, but using a compile-time constant for the logging
468 // severity. This saves space at the call site, since passing an empty struct
469 // is generally the same as not passing an argument at all.
470 template <LoggingSeverity S>
471 RTC_NO_INLINE LogMessage(const char* file,
472 int line,
473 std::integral_constant<LoggingSeverity, S>)
474 : LogMessage(file, line, S) {}
475
Artem Titov6a4a1462019-11-26 16:24:46 +0100476#if RTC_LOG_ENABLED()
477 LogMessage(const char* file, int line, LoggingSeverity sev);
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200478 LogMessage(const char* file,
479 int line,
480 LoggingSeverity sev,
Karl Wibergab4f1c12018-05-04 10:42:28 +0200481 LogErrorContext err_ctx,
482 int err);
Tommie51a0a82018-02-27 15:30:29 +0100483#if defined(WEBRTC_ANDROID)
484 LogMessage(const char* file, int line, LoggingSeverity sev, const char* tag);
485#endif
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200486 ~LogMessage();
487
Byoungchan Lee14af7622022-01-12 05:24:58 +0900488 LogMessage(const LogMessage&) = delete;
489 LogMessage& operator=(const LogMessage&) = delete;
490
Karl Wibergcefc4652018-05-23 23:20:38 +0200491 void AddTag(const char* tag);
Jonas Olssond8c50782018-09-07 11:21:28 +0200492 rtc::StringBuilder& stream();
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200493 // Returns the time at which this function was called for the first time.
494 // The time will be used as the logging start time.
495 // If this is not called externally, the LogMessage ctor also calls it, in
496 // which case the logging start time will be the time of the first LogMessage
497 // instance is created.
498 static int64_t LogStartTime();
Artem Titov96e3b992021-07-26 16:03:14 +0200499 // Returns the wall clock equivalent of `LogStartTime`, in seconds from the
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200500 // epoch.
501 static uint32_t WallClockStartTime();
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200502 // LogThreads: Display the thread identifier of the current thread
503 static void LogThreads(bool on = true);
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200504 // LogTimestamps: Display the elapsed time of the program
505 static void LogTimestamps(bool on = true);
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200506 // These are the available logging channels
507 // Debug: Debug console on Windows, otherwise stderr
508 static void LogToDebug(LoggingSeverity min_sev);
Jonas Olsson2b6f1352018-02-15 11:57:03 +0100509 static LoggingSeverity GetLogToDebug();
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200510 // Sets whether logs will be directed to stderr in debug mode.
511 static void SetLogToStderr(bool log_to_stderr);
Danil Chapovalovb9f69022019-10-21 09:19:10 +0200512 // Stream: Any non-blocking stream interface.
Artem Titov96e3b992021-07-26 16:03:14 +0200513 // Installs the `stream` to collect logs with severtiy `min_sev` or higher.
514 // `stream` must live until deinstalled by RemoveLogToStream.
515 // If `stream` is the first stream added to the system, we might miss some
Markus Handell531bd0f2020-07-08 10:58:19 +0200516 // early concurrent log statement happening from another thread happening near
517 // this instant.
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200518 static void AddLogToStream(LogSink* stream, LoggingSeverity min_sev);
Markus Handell531bd0f2020-07-08 10:58:19 +0200519 // Removes the specified stream, without destroying it. When the method
Artem Titov96e3b992021-07-26 16:03:14 +0200520 // has completed, it's guaranteed that `stream` will receive no more logging
Markus Handell531bd0f2020-07-08 10:58:19 +0200521 // calls.
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200522 static void RemoveLogToStream(LogSink* stream);
Danil Chapovalovb9f69022019-10-21 09:19:10 +0200523 // Returns the severity for the specified stream, of if none is specified,
524 // the minimum stream severity.
525 static int GetLogToStream(LogSink* stream = nullptr);
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200526 // Testing against MinLogSeverity allows code to avoid potentially expensive
527 // logging operations by pre-checking the logging level.
Jonas Olsson2b6f1352018-02-15 11:57:03 +0100528 static int GetMinLogSeverity();
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200529 // Parses the provided parameter stream to configure the options above.
530 // Useful for configuring logging from the command line.
Ali Tofigh2ab914c2022-04-13 12:55:15 +0200531 static void ConfigureLogging(absl::string_view params);
Artem Titov96e3b992021-07-26 16:03:14 +0200532 // Checks the current global debug severity and if the `streams_` collection
533 // is empty. If `severity` is smaller than the global severity and if the
534 // `streams_` collection is empty, the LogMessage will be considered a noop
Jonas Olssond8c50782018-09-07 11:21:28 +0200535 // LogMessage.
536 static bool IsNoop(LoggingSeverity severity);
Karl Wibergdd7df5c2020-09-22 11:07:53 +0200537 // Version of IsNoop that uses fewer instructions at the call site, since the
538 // caller doesn't have to pass an argument.
539 template <LoggingSeverity S>
540 RTC_NO_INLINE static bool IsNoop() {
541 return IsNoop(S);
542 }
Artem Titov6a4a1462019-11-26 16:24:46 +0100543#else
544 // Next methods do nothing; no one will call these functions.
545 LogMessage(const char* file, int line, LoggingSeverity sev) {}
546 LogMessage(const char* file,
547 int line,
548 LoggingSeverity sev,
549 LogErrorContext err_ctx,
550 int err) {}
551#if defined(WEBRTC_ANDROID)
552 LogMessage(const char* file, int line, LoggingSeverity sev, const char* tag) {
553 }
554#endif
Artem Titov6a4a1462019-11-26 16:24:46 +0100555 ~LogMessage() = default;
556
557 inline void AddTag(const char* tag) {}
558 inline rtc::StringBuilder& stream() { return print_stream_; }
559 inline static int64_t LogStartTime() { return 0; }
560 inline static uint32_t WallClockStartTime() { return 0; }
561 inline static void LogThreads(bool on = true) {}
562 inline static void LogTimestamps(bool on = true) {}
563 inline static void LogToDebug(LoggingSeverity min_sev) {}
564 inline static LoggingSeverity GetLogToDebug() {
565 return LoggingSeverity::LS_INFO;
566 }
567 inline static void SetLogToStderr(bool log_to_stderr) {}
568 inline static void AddLogToStream(LogSink* stream, LoggingSeverity min_sev) {}
569 inline static void RemoveLogToStream(LogSink* stream) {}
570 inline static int GetLogToStream(LogSink* stream = nullptr) { return 0; }
571 inline static int GetMinLogSeverity() { return 0; }
Ali Tofigh2ab914c2022-04-13 12:55:15 +0200572 inline static void ConfigureLogging(absl::string_view params) {}
Karl Wiberg0e884382020-09-22 09:34:45 +0200573 static constexpr bool IsNoop(LoggingSeverity severity) { return true; }
Karl Wibergdd7df5c2020-09-22 11:07:53 +0200574 template <LoggingSeverity S>
575 static constexpr bool IsNoop() {
576 return IsNoop(S);
577 }
Artem Titov6a4a1462019-11-26 16:24:46 +0100578#endif // RTC_LOG_ENABLED()
Jonas Olssond8c50782018-09-07 11:21:28 +0200579
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200580 private:
Tommifef05002018-02-27 13:51:08 +0100581 friend class LogMessageForTesting;
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200582
Artem Titov6a4a1462019-11-26 16:24:46 +0100583#if RTC_LOG_ENABLED()
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200584 // Updates min_sev_ appropriately when debug sinks change.
585 static void UpdateMinLogSeverity();
586
Mirko Bonadei96191f82022-08-03 08:12:33 +0000587 // This writes out the actual log messages.
588 static void OutputToDebug(const LogLineRef& log_line_ref);
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200589
Tommifef05002018-02-27 13:51:08 +0100590 // Called from the dtor (or from a test) to append optional extra error
591 // information to the log stream and a newline character.
592 void FinishPrintStream();
593
Mirko Bonadei96191f82022-08-03 08:12:33 +0000594 LogLineRef log_line_;
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200595
596 // String data generated in the constructor, that should be appended to
597 // the message before output.
598 std::string extra_;
599
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200600 // The output streams and their associated severities
Danil Chapovalovb9f69022019-10-21 09:19:10 +0200601 static LogSink* streams_;
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200602
Artem Titov96e3b992021-07-26 16:03:14 +0200603 // Holds true with high probability if `streams_` is empty, false with high
Markus Handellce1ff6f2020-07-08 08:52:48 +0200604 // probability otherwise. Operated on with std::memory_order_relaxed because
Markus Handell531bd0f2020-07-08 10:58:19 +0200605 // it's ok to lose or log some additional statements near the instant streams
Markus Handellce1ff6f2020-07-08 08:52:48 +0200606 // are added/removed.
607 static std::atomic<bool> streams_empty_;
608
Mirko Bonadei96191f82022-08-03 08:12:33 +0000609 // Flags for formatting options and their potential values.
610 static bool log_thread_;
611 static bool log_timestamp_;
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200612
613 // Determines if logs will be directed to stderr in debug mode.
614 static bool log_to_stderr_;
Artem Titov6a4a1462019-11-26 16:24:46 +0100615#else // RTC_LOG_ENABLED()
616 // Next methods do nothing; no one will call these functions.
617 inline static void UpdateMinLogSeverity() {}
618#if defined(WEBRTC_ANDROID)
Mirko Bonadei96191f82022-08-03 08:12:33 +0000619 inline static void OutputToDebug(absl::string_view filename,
620 int line,
621 absl::string_view msg,
Artem Titov6a4a1462019-11-26 16:24:46 +0100622 LoggingSeverity severity,
623 const char* tag) {}
624#else
Mirko Bonadei96191f82022-08-03 08:12:33 +0000625 inline static void OutputToDebug(absl::string_view filename,
626 int line,
627 absl::string_view msg,
Artem Titov6a4a1462019-11-26 16:24:46 +0100628 LoggingSeverity severity) {}
629#endif // defined(WEBRTC_ANDROID)
630 inline void FinishPrintStream() {}
631#endif // RTC_LOG_ENABLED()
632
633 // The stringbuilder that buffers the formatted message before output
634 rtc::StringBuilder print_stream_;
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200635};
636
637//////////////////////////////////////////////////////////////////////
638// Logging Helpers
639//////////////////////////////////////////////////////////////////////
640
Karl Wibergdd7df5c2020-09-22 11:07:53 +0200641#define RTC_LOG_FILE_LINE(sev, file, line) \
642 ::rtc::webrtc_logging_impl::LogCall() & \
643 ::rtc::webrtc_logging_impl::LogStreamer<>() \
644 << ::rtc::webrtc_logging_impl::LogMetadata(file, line, sev)
Jonas Olsson8a7916b2018-09-06 09:50:23 +0200645
Karl Wibergdd7df5c2020-09-22 11:07:53 +0200646#define RTC_LOG(sev) \
647 !rtc::LogMessage::IsNoop<::rtc::sev>() && \
648 RTC_LOG_FILE_LINE(::rtc::sev, __FILE__, __LINE__)
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200649
Karl Wibergcefc4652018-05-23 23:20:38 +0200650// The _V version is for when a variable is passed in.
Karl Wibergdd7df5c2020-09-22 11:07:53 +0200651#define RTC_LOG_V(sev) \
652 !rtc::LogMessage::IsNoop(sev) && RTC_LOG_FILE_LINE(sev, __FILE__, __LINE__)
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200653
654// The _F version prefixes the message with the current function name.
655#if (defined(__GNUC__) && !defined(NDEBUG)) || defined(WANT_PRETTY_LOG_F)
Mirko Bonadei8ed8e562017-10-27 09:43:53 +0200656#define RTC_LOG_F(sev) RTC_LOG(sev) << __PRETTY_FUNCTION__ << ": "
Yves Gerey665174f2018-06-19 15:03:05 +0200657#define RTC_LOG_T_F(sev) \
658 RTC_LOG(sev) << this << ": " << __PRETTY_FUNCTION__ << ": "
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200659#else
Mirko Bonadei8ed8e562017-10-27 09:43:53 +0200660#define RTC_LOG_F(sev) RTC_LOG(sev) << __FUNCTION__ << ": "
Patrik Höglundc2962552017-11-17 13:40:22 +0000661#define RTC_LOG_T_F(sev) RTC_LOG(sev) << this << ": " << __FUNCTION__ << ": "
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200662#endif
663
Jiawei Ou14e5f0b2020-03-04 13:38:02 -0800664#define RTC_LOG_CHECK_LEVEL(sev) ::rtc::LogCheckLevel(::rtc::sev)
665#define RTC_LOG_CHECK_LEVEL_V(sev) ::rtc::LogCheckLevel(sev)
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200666
667inline bool LogCheckLevel(LoggingSeverity sev) {
668 return (LogMessage::GetMinLogSeverity() <= sev);
669}
670
Karl Wiberg92e37962020-09-22 13:22:20 +0200671#define RTC_LOG_E(sev, ctx, err) \
672 !rtc::LogMessage::IsNoop<::rtc::sev>() && \
673 ::rtc::webrtc_logging_impl::LogCall() & \
674 ::rtc::webrtc_logging_impl::LogStreamer<>() \
675 << ::rtc::webrtc_logging_impl::LogMetadataErr { \
676 {__FILE__, __LINE__, ::rtc::sev}, ::rtc::ERRCTX_##ctx, (err) \
Jonas Olssona4d87372019-07-05 19:08:33 +0200677 }
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200678
Mirko Bonadei8ed8e562017-10-27 09:43:53 +0200679#define RTC_LOG_T(sev) RTC_LOG(sev) << this << ": "
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200680
Yves Gerey665174f2018-06-19 15:03:05 +0200681#define RTC_LOG_ERRNO_EX(sev, err) RTC_LOG_E(sev, ERRNO, err)
682#define RTC_LOG_ERRNO(sev) RTC_LOG_ERRNO_EX(sev, errno)
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200683
684#if defined(WEBRTC_WIN)
Yves Gerey665174f2018-06-19 15:03:05 +0200685#define RTC_LOG_GLE_EX(sev, err) RTC_LOG_E(sev, HRESULT, err)
Karl Wibergcefc4652018-05-23 23:20:38 +0200686#define RTC_LOG_GLE(sev) RTC_LOG_GLE_EX(sev, static_cast<int>(GetLastError()))
Yves Gerey665174f2018-06-19 15:03:05 +0200687#define RTC_LOG_ERR_EX(sev, err) RTC_LOG_GLE_EX(sev, err)
688#define RTC_LOG_ERR(sev) RTC_LOG_GLE(sev)
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200689#elif defined(__native_client__) && __native_client__
Yves Gerey665174f2018-06-19 15:03:05 +0200690#define RTC_LOG_ERR_EX(sev, err) RTC_LOG(sev)
691#define RTC_LOG_ERR(sev) RTC_LOG(sev)
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200692#elif defined(WEBRTC_POSIX)
Yves Gerey665174f2018-06-19 15:03:05 +0200693#define RTC_LOG_ERR_EX(sev, err) RTC_LOG_ERRNO_EX(sev, err)
694#define RTC_LOG_ERR(sev) RTC_LOG_ERRNO(sev)
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200695#endif // WEBRTC_WIN
696
Karl Wibergcefc4652018-05-23 23:20:38 +0200697#ifdef WEBRTC_ANDROID
698
699namespace webrtc_logging_impl {
700// TODO(kwiberg): Replace these with absl::string_view.
Yves Gerey665174f2018-06-19 15:03:05 +0200701inline const char* AdaptString(const char* str) {
702 return str;
703}
704inline const char* AdaptString(const std::string& str) {
705 return str.c_str();
706}
Karl Wibergcefc4652018-05-23 23:20:38 +0200707} // namespace webrtc_logging_impl
708
Karl Wiberg92e37962020-09-22 13:22:20 +0200709#define RTC_LOG_TAG(sev, tag) \
710 !rtc::LogMessage::IsNoop(sev) && \
711 ::rtc::webrtc_logging_impl::LogCall() & \
712 ::rtc::webrtc_logging_impl::LogStreamer<>() \
713 << ::rtc::webrtc_logging_impl::LogMetadataTag { \
714 sev, ::rtc::webrtc_logging_impl::AdaptString(tag) \
Jonas Olssona4d87372019-07-05 19:08:33 +0200715 }
Karl Wibergcefc4652018-05-23 23:20:38 +0200716
Tommie51a0a82018-02-27 15:30:29 +0100717#else
Karl Wibergcefc4652018-05-23 23:20:38 +0200718
Tommie51a0a82018-02-27 15:30:29 +0100719// DEPRECATED. This macro is only intended for Android.
Karl Wibergcefc4652018-05-23 23:20:38 +0200720#define RTC_LOG_TAG(sev, tag) RTC_LOG_V(sev)
721
Tommie51a0a82018-02-27 15:30:29 +0100722#endif
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200723
Fredrik Solenbergb3d7cac2017-11-17 15:22:37 +0100724// The RTC_DLOG macros are equivalent to their RTC_LOG counterparts except that
725// they only generate code in debug builds.
726#if RTC_DLOG_IS_ON
727#define RTC_DLOG(sev) RTC_LOG(sev)
728#define RTC_DLOG_V(sev) RTC_LOG_V(sev)
729#define RTC_DLOG_F(sev) RTC_LOG_F(sev)
730#else
Mirko Bonadeif1df04b2020-03-23 19:53:23 +0100731#define RTC_DLOG_EAT_STREAM_PARAMS() \
732 while (false) \
733 ::rtc::webrtc_logging_impl::LogMessageVoidify() & \
734 (::rtc::webrtc_logging_impl::LogStreamer<>())
Karl Wibergcefc4652018-05-23 23:20:38 +0200735#define RTC_DLOG(sev) RTC_DLOG_EAT_STREAM_PARAMS()
736#define RTC_DLOG_V(sev) RTC_DLOG_EAT_STREAM_PARAMS()
737#define RTC_DLOG_F(sev) RTC_DLOG_EAT_STREAM_PARAMS()
Fredrik Solenbergb3d7cac2017-11-17 15:22:37 +0100738#endif
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200739
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200740} // namespace rtc
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000741
Mirko Bonadei92ea95e2017-09-15 06:47:31 +0200742#endif // RTC_BASE_LOGGING_H_