blob: d59b9a0ef74794b756e1a11651e7e1d87f00e817 [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.
Per Kjellander4d419132022-09-30 12:50:41 +020024// RTC_LOG_IF(sev, condition) logs the given stream at severitye "sev" if
25// "condition" is true.
Mirko Bonadei8ed8e562017-10-27 09:43:53 +020026// RTC_LOG_V(sev) Like RTC_LOG(), but sev is a run-time variable of the
27// LoggingSeverity type (basically, it just doesn't prepend the namespace).
28// RTC_LOG_F(sev) Like RTC_LOG(), but includes the name of the current function.
Per Kjellander4d419132022-09-30 12:50:41 +020029// RTC_LOG_IF_F(sev, condition), Like RTC_LOG_IF(), but includes the name of
30// the current function.
Mirko Bonadei8ed8e562017-10-27 09:43:53 +020031// RTC_LOG_T(sev) Like RTC_LOG(), but includes the this pointer.
32// RTC_LOG_T_F(sev) Like RTC_LOG_F(), but includes the this pointer.
Tommie51a0a82018-02-27 15:30:29 +010033// RTC_LOG_GLE(sev [, mod]) attempt to add a string description of the
34// HRESULT returned by GetLastError.
Mirko Bonadei8ed8e562017-10-27 09:43:53 +020035// RTC_LOG_ERRNO(sev) attempts to add a string description of an errno-derived
henrike@webrtc.orgf0488722014-05-13 18:00:26 +000036// error. errno and associated facilities exist on both Windows and POSIX,
37// but on Windows they only apply to the C/C++ runtime.
Mirko Bonadei8ed8e562017-10-27 09:43:53 +020038// RTC_LOG_ERR(sev) is an alias for the platform's normal error system, i.e.
39// _GLE on Windows and _ERRNO on POSIX.
henrike@webrtc.orgf0488722014-05-13 18:00:26 +000040// (The above three also all have _EX versions that let you specify the error
41// code, rather than using the last one.)
Mirko Bonadei8ed8e562017-10-27 09:43:53 +020042// RTC_LOG_E(sev, ctx, err, ...) logs a detailed error interpreted using the
henrike@webrtc.orgf0488722014-05-13 18:00:26 +000043// specified context.
Mirko Bonadei8ed8e562017-10-27 09:43:53 +020044// RTC_LOG_CHECK_LEVEL(sev) (and RTC_LOG_CHECK_LEVEL_V(sev)) can be used as a
45// test before performing expensive or sensitive operations whose sole
46// purpose is to output logging data at the desired level.
henrike@webrtc.orgf0488722014-05-13 18:00:26 +000047
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020048#ifndef RTC_BASE_LOGGING_H_
49#define RTC_BASE_LOGGING_H_
henrike@webrtc.orgf0488722014-05-13 18:00:26 +000050
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +020051#include <errno.h>
mostynbe38e4f62016-05-12 01:08:20 -070052
Markus Handellce1ff6f2020-07-08 08:52:48 +020053#include <atomic>
Jonas Olsson941a07c2018-09-13 10:07:07 +020054#include <sstream> // no-presubmit-check TODO(webrtc:8982)
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +020055#include <string>
Evan Shrubsole7765f9e2022-04-25 11:04:12 +020056#include <type_traits>
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +020057#include <utility>
58
Danil Chapovalove9041612021-02-22 12:43:39 +010059#include "absl/base/attributes.h"
Sebastian Janssonf4e085a2019-05-20 18:34:07 +020060#include "absl/meta/type_traits.h"
Jonas Olssonf2ce37c2018-09-12 15:32:47 +020061#include "absl/strings/string_view.h"
Mirko Bonadei96191f82022-08-03 08:12:33 +000062#include "absl/types/optional.h"
63#include "api/units/timestamp.h"
64#include "rtc_base/platform_thread_types.h"
Jonas Olssond8c50782018-09-07 11:21:28 +020065#include "rtc_base/strings/string_builder.h"
Karl Wibergcefc4652018-05-23 23:20:38 +020066#include "rtc_base/system/inline.h"
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +020067
Fredrik Solenbergb3d7cac2017-11-17 15:22:37 +010068#if !defined(NDEBUG) || defined(DLOG_ALWAYS_ON)
69#define RTC_DLOG_IS_ON 1
70#else
71#define RTC_DLOG_IS_ON 0
72#endif
73
Artem Titov6a4a1462019-11-26 16:24:46 +010074#if defined(RTC_DISABLE_LOGGING)
75#define RTC_LOG_ENABLED() 0
76#else
77#define RTC_LOG_ENABLED() 1
78#endif
79
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +020080namespace rtc {
81
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +020082//////////////////////////////////////////////////////////////////////
Harald Alvestrand57869da2022-03-09 10:52:14 +000083// The meanings of the levels are:
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +020084// LS_VERBOSE: This level is for data which we do not want to appear in the
85// normal debug log, but should appear in diagnostic logs.
86// LS_INFO: Chatty level used in debugging for all sorts of things, the default
87// in debug builds.
88// LS_WARNING: Something that may warrant investigation.
89// LS_ERROR: Something that should not have occurred.
90// LS_NONE: Don't log.
91enum LoggingSeverity {
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +020092 LS_VERBOSE,
93 LS_INFO,
94 LS_WARNING,
95 LS_ERROR,
96 LS_NONE,
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +020097};
98
99// LogErrorContext assists in interpreting the meaning of an error value.
100enum LogErrorContext {
101 ERRCTX_NONE,
Jonas Olssona4d87372019-07-05 19:08:33 +0200102 ERRCTX_ERRNO, // System-local errno
103 ERRCTX_HRESULT, // Windows HRESULT
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200104
105 // Abbreviations for LOG_E macro
Jonas Olssona4d87372019-07-05 19:08:33 +0200106 ERRCTX_EN = ERRCTX_ERRNO, // LOG_E(sev, EN, x)
107 ERRCTX_HR = ERRCTX_HRESULT, // LOG_E(sev, HR, x)
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200108};
109
Danil Chapovalovb9f69022019-10-21 09:19:10 +0200110class LogMessage;
Mirko Bonadei96191f82022-08-03 08:12:33 +0000111
112// LogLineRef encapsulates all the information required to generate a log line.
113// It is used both internally to LogMessage but also as a parameter to
114// LogSink::OnLogMessage, allowing custom LogSinks to format the log in
115// the most flexible way.
116class LogLineRef {
117 public:
Mirko Bonadei73f0c212022-08-03 13:18:30 +0000118 absl::string_view message() const { return message_; }
119 absl::string_view filename() const { return filename_; }
120 int line() const { return line_; }
121 absl::optional<PlatformThreadId> thread_id() const { return thread_id_; }
122 webrtc::Timestamp timestamp() const { return timestamp_; }
123 absl::string_view tag() const { return tag_; }
Mirko Bonadei96191f82022-08-03 08:12:33 +0000124 LoggingSeverity severity() const { return severity_; }
125
Mirko Bonadei821b92a2022-08-03 15:04:48 +0000126#if RTC_LOG_ENABLED()
Mirko Bonadei96191f82022-08-03 08:12:33 +0000127 std::string DefaultLogLine() const;
Mirko Bonadei821b92a2022-08-03 15:04:48 +0000128#else
129 std::string DefaultLogLine() const { return ""; }
130#endif
Mirko Bonadei96191f82022-08-03 08:12:33 +0000131
132 private:
133 friend class LogMessage;
134 void set_message(std::string message) { message_ = std::move(message); }
135 void set_filename(absl::string_view filename) { filename_ = filename; }
136 void set_line(int line) { line_ = line; }
137 void set_thread_id(absl::optional<PlatformThreadId> thread_id) {
138 thread_id_ = thread_id;
139 }
140 void set_timestamp(webrtc::Timestamp timestamp) { timestamp_ = timestamp; }
141 void set_tag(absl::string_view tag) { tag_ = tag; }
142 void set_severity(LoggingSeverity severity) { severity_ = severity; }
143
144 std::string message_;
145 absl::string_view filename_;
146 int line_ = 0;
147 absl::optional<PlatformThreadId> thread_id_;
148 webrtc::Timestamp timestamp_ = webrtc::Timestamp::MinusInfinity();
149 // The default Android debug output tag.
150 absl::string_view tag_ = "libjingle";
151 // The severity level of this message
152 LoggingSeverity severity_;
153};
154
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200155// Virtual sink interface that can receive log messages.
156class LogSink {
157 public:
158 LogSink() {}
159 virtual ~LogSink() {}
Paulina Hensmanf1e3cb42018-06-20 14:07:05 +0200160 virtual void OnLogMessage(const std::string& msg,
161 LoggingSeverity severity,
162 const char* tag);
Jiawei Ou3ea18782018-10-31 23:14:24 -0700163 virtual void OnLogMessage(const std::string& message,
164 LoggingSeverity severity);
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200165 virtual void OnLogMessage(const std::string& message) = 0;
Danil Chapovalovb9f69022019-10-21 09:19:10 +0200166
Ali Tofigh6364d082022-03-14 13:32:04 +0100167 virtual void OnLogMessage(absl::string_view msg,
168 LoggingSeverity severity,
169 const char* tag);
170 virtual void OnLogMessage(absl::string_view message,
171 LoggingSeverity severity);
172 virtual void OnLogMessage(absl::string_view message);
Mirko Bonadei96191f82022-08-03 08:12:33 +0000173 virtual void OnLogMessage(const LogLineRef& line);
Ali Tofigh6364d082022-03-14 13:32:04 +0100174
Danil Chapovalovb9f69022019-10-21 09:19:10 +0200175 private:
176 friend class ::rtc::LogMessage;
Artem Titov6a4a1462019-11-26 16:24:46 +0100177#if RTC_LOG_ENABLED()
Danil Chapovalovb9f69022019-10-21 09:19:10 +0200178 // Members for LogMessage class to keep linked list of the registered sinks.
179 LogSink* next_ = nullptr;
180 LoggingSeverity min_severity_;
Artem Titov6a4a1462019-11-26 16:24:46 +0100181#endif
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200182};
183
Karl Wibergcefc4652018-05-23 23:20:38 +0200184namespace webrtc_logging_impl {
185
186class LogMetadata {
187 public:
188 LogMetadata(const char* file, int line, LoggingSeverity severity)
189 : file_(file),
190 line_and_sev_(static_cast<uint32_t>(line) << 3 | severity) {}
191 LogMetadata() = default;
192
193 const char* File() const { return file_; }
194 int Line() const { return line_and_sev_ >> 3; }
195 LoggingSeverity Severity() const {
196 return static_cast<LoggingSeverity>(line_and_sev_ & 0x7);
197 }
198
199 private:
200 const char* file_;
201
202 // Line number and severity, the former in the most significant 29 bits, the
203 // latter in the least significant 3 bits. (This is an optimization; since
204 // both numbers are usually compile-time constants, this way we can load them
205 // both with a single instruction.)
206 uint32_t line_and_sev_;
207};
208static_assert(std::is_trivial<LogMetadata>::value, "");
209
210struct LogMetadataErr {
211 LogMetadata meta;
212 LogErrorContext err_ctx;
213 int err;
214};
215
216#ifdef WEBRTC_ANDROID
217struct LogMetadataTag {
218 LoggingSeverity severity;
219 const char* tag;
220};
221#endif
222
223enum class LogArgType : int8_t {
224 kEnd = 0,
225 kInt,
226 kLong,
227 kLongLong,
228 kUInt,
229 kULong,
230 kULongLong,
231 kDouble,
232 kLongDouble,
233 kCharP,
234 kStdString,
Jonas Olssonf2ce37c2018-09-12 15:32:47 +0200235 kStringView,
Karl Wibergcefc4652018-05-23 23:20:38 +0200236 kVoidP,
237 kLogMetadata,
238 kLogMetadataErr,
239#ifdef WEBRTC_ANDROID
240 kLogMetadataTag,
241#endif
242};
243
244// Wrapper for log arguments. Only ever make values of this type with the
245// MakeVal() functions.
246template <LogArgType N, typename T>
247struct Val {
248 static constexpr LogArgType Type() { return N; }
249 T GetVal() const { return val; }
250 T val;
251};
252
Sebastian Janssonb1138622019-04-11 16:48:15 +0200253// Case for when we need to construct a temp string and then print that.
254// (We can't use Val<CheckArgType::kStdString, const std::string*>
255// because we need somewhere to store the temp string.)
256struct ToStringVal {
Karl Wibergcefc4652018-05-23 23:20:38 +0200257 static constexpr LogArgType Type() { return LogArgType::kStdString; }
258 const std::string* GetVal() const { return &val; }
259 std::string val;
260};
261
262inline Val<LogArgType::kInt, int> MakeVal(int x) {
263 return {x};
264}
265inline Val<LogArgType::kLong, long> MakeVal(long x) {
266 return {x};
267}
268inline Val<LogArgType::kLongLong, long long> MakeVal(long long x) {
269 return {x};
270}
271inline Val<LogArgType::kUInt, unsigned int> MakeVal(unsigned int x) {
272 return {x};
273}
274inline Val<LogArgType::kULong, unsigned long> MakeVal(unsigned long x) {
275 return {x};
276}
277inline Val<LogArgType::kULongLong, unsigned long long> MakeVal(
278 unsigned long long x) {
279 return {x};
280}
281
282inline Val<LogArgType::kDouble, double> MakeVal(double x) {
283 return {x};
284}
285inline Val<LogArgType::kLongDouble, long double> MakeVal(long double x) {
286 return {x};
287}
288
289inline Val<LogArgType::kCharP, const char*> MakeVal(const char* x) {
290 return {x};
291}
292inline Val<LogArgType::kStdString, const std::string*> MakeVal(
293 const std::string& x) {
294 return {&x};
295}
Jonas Olssonf2ce37c2018-09-12 15:32:47 +0200296inline Val<LogArgType::kStringView, const absl::string_view*> MakeVal(
297 const absl::string_view& x) {
298 return {&x};
299}
Karl Wibergcefc4652018-05-23 23:20:38 +0200300
301inline Val<LogArgType::kVoidP, const void*> MakeVal(const void* x) {
302 return {x};
303}
304
305inline Val<LogArgType::kLogMetadata, LogMetadata> MakeVal(
306 const LogMetadata& x) {
307 return {x};
308}
309inline Val<LogArgType::kLogMetadataErr, LogMetadataErr> MakeVal(
310 const LogMetadataErr& x) {
311 return {x};
312}
313
Amit Hilbuch10c5a932019-03-18 13:09:18 -0700314// The enum class types are not implicitly convertible to arithmetic types.
Sebastian Janssonf4e085a2019-05-20 18:34:07 +0200315template <typename T,
316 absl::enable_if_t<std::is_enum<T>::value &&
317 !std::is_arithmetic<T>::value>* = nullptr>
318inline decltype(MakeVal(std::declval<absl::underlying_type_t<T>>())) MakeVal(
319 T x) {
320 return {static_cast<absl::underlying_type_t<T>>(x)};
Amit Hilbuch10c5a932019-03-18 13:09:18 -0700321}
322
Karl Wibergcefc4652018-05-23 23:20:38 +0200323#ifdef WEBRTC_ANDROID
324inline Val<LogArgType::kLogMetadataTag, LogMetadataTag> MakeVal(
325 const LogMetadataTag& x) {
326 return {x};
327}
328#endif
329
Sebastian Janssonf4e085a2019-05-20 18:34:07 +0200330template <typename T, class = void>
Sebastian Janssonb1138622019-04-11 16:48:15 +0200331struct has_to_log_string : std::false_type {};
332template <typename T>
Evan Shrubsole7765f9e2022-04-25 11:04:12 +0200333struct has_to_log_string<T,
334 absl::enable_if_t<std::is_convertible<
335 decltype(ToLogString(std::declval<T>())),
336 std::string>::value>> : std::true_type {};
337
338template <typename T, absl::enable_if_t<has_to_log_string<T>::value>* = nullptr>
339ToStringVal MakeVal(const T& x) {
340 return {ToLogString(x)};
341}
Sebastian Janssonb1138622019-04-11 16:48:15 +0200342
Karl Wibergcefc4652018-05-23 23:20:38 +0200343// Handle arbitrary types other than the above by falling back to stringstream.
344// TODO(bugs.webrtc.org/9278): Get rid of this overload when callers don't need
345// it anymore. No in-tree caller does, but some external callers still do.
346template <
347 typename T,
Sebastian Janssonf4e085a2019-05-20 18:34:07 +0200348 typename T1 = absl::decay_t<T>,
349 absl::enable_if_t<std::is_class<T1>::value &&
350 !std::is_same<T1, std::string>::value &&
351 !std::is_same<T1, LogMetadata>::value &&
352 !has_to_log_string<T1>::value &&
Karl Wibergcefc4652018-05-23 23:20:38 +0200353#ifdef WEBRTC_ANDROID
Sebastian Janssonf4e085a2019-05-20 18:34:07 +0200354 !std::is_same<T1, LogMetadataTag>::value &&
Karl Wibergcefc4652018-05-23 23:20:38 +0200355#endif
Sebastian Janssonf4e085a2019-05-20 18:34:07 +0200356 !std::is_same<T1, LogMetadataErr>::value>* = nullptr>
Sebastian Janssonb1138622019-04-11 16:48:15 +0200357ToStringVal MakeVal(const T& x) {
Karl Wibergcefc4652018-05-23 23:20:38 +0200358 std::ostringstream os; // no-presubmit-check TODO(webrtc:8982)
359 os << x;
360 return {os.str()};
361}
362
Artem Titov6a4a1462019-11-26 16:24:46 +0100363#if RTC_LOG_ENABLED()
Karl Wibergcefc4652018-05-23 23:20:38 +0200364void Log(const LogArgType* fmt, ...);
Artem Titov6a4a1462019-11-26 16:24:46 +0100365#else
366inline void Log(const LogArgType* fmt, ...) {
367 // Do nothing, shouldn't be invoked
368}
369#endif
Karl Wibergcefc4652018-05-23 23:20:38 +0200370
371// Ephemeral type that represents the result of the logging << operator.
372template <typename... Ts>
373class LogStreamer;
374
375// Base case: Before the first << argument.
376template <>
377class LogStreamer<> final {
378 public:
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<<(U arg) const {
384 return LogStreamer<V>(MakeVal(arg), this);
Karl Wibergcefc4652018-05-23 23:20:38 +0200385 }
386
Amit Hilbuch10c5a932019-03-18 13:09:18 -0700387 template <typename U,
Sebastian Janssonf4e085a2019-05-20 18:34:07 +0200388 typename V = decltype(MakeVal(std::declval<U>())),
389 absl::enable_if_t<!std::is_arithmetic<U>::value &&
390 !std::is_enum<U>::value>* = nullptr>
391 RTC_FORCE_INLINE LogStreamer<V> operator<<(const U& arg) const {
392 return LogStreamer<V>(MakeVal(arg), this);
Karl Wibergcefc4652018-05-23 23:20:38 +0200393 }
394
395 template <typename... Us>
396 RTC_FORCE_INLINE static void Call(const Us&... args) {
397 static constexpr LogArgType t[] = {Us::Type()..., LogArgType::kEnd};
398 Log(t, args.GetVal()...);
399 }
400};
401
402// Inductive case: We've already seen at least one << argument. The most recent
403// one had type `T`, and the earlier ones had types `Ts`.
404template <typename T, typename... Ts>
405class LogStreamer<T, Ts...> final {
406 public:
407 RTC_FORCE_INLINE LogStreamer(T arg, const LogStreamer<Ts...>* prior)
408 : arg_(arg), prior_(prior) {}
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<<(U arg) const {
415 return LogStreamer<V, T, Ts...>(MakeVal(arg), this);
Karl Wibergcefc4652018-05-23 23:20:38 +0200416 }
417
Amit Hilbuch10c5a932019-03-18 13:09:18 -0700418 template <typename U,
Sebastian Janssonf4e085a2019-05-20 18:34:07 +0200419 typename V = decltype(MakeVal(std::declval<U>())),
420 absl::enable_if_t<!std::is_arithmetic<U>::value &&
421 !std::is_enum<U>::value>* = nullptr>
422 RTC_FORCE_INLINE LogStreamer<V, T, Ts...> operator<<(const U& arg) const {
423 return LogStreamer<V, T, Ts...>(MakeVal(arg), this);
Karl Wibergcefc4652018-05-23 23:20:38 +0200424 }
425
426 template <typename... Us>
427 RTC_FORCE_INLINE void Call(const Us&... args) const {
428 prior_->Call(arg_, args...);
429 }
430
431 private:
432 // The most recent argument.
433 T arg_;
434
435 // Earlier arguments.
436 const LogStreamer<Ts...>* prior_;
437};
438
439class LogCall final {
440 public:
441 // This can be any binary operator with precedence lower than <<.
Artem Titov6a4a1462019-11-26 16:24:46 +0100442 // We return bool here to be able properly remove logging if
443 // RTC_DISABLE_LOGGING is defined.
Karl Wibergcefc4652018-05-23 23:20:38 +0200444 template <typename... Ts>
Artem Titov6a4a1462019-11-26 16:24:46 +0100445 RTC_FORCE_INLINE bool operator&(const LogStreamer<Ts...>& streamer) {
Karl Wibergcefc4652018-05-23 23:20:38 +0200446 streamer.Call();
Artem Titov6a4a1462019-11-26 16:24:46 +0100447 return true;
Karl Wibergcefc4652018-05-23 23:20:38 +0200448 }
449};
450
Mirko Bonadeif1df04b2020-03-23 19:53:23 +0100451// This class is used to explicitly ignore values in the conditional
452// logging macros. This avoids compiler warnings like "value computed
453// is not used" and "statement has no effect".
454class LogMessageVoidify {
455 public:
456 LogMessageVoidify() = default;
457 // This has to be an operator with a precedence lower than << but
458 // higher than ?:
459 template <typename... Ts>
460 void operator&(LogStreamer<Ts...>&& streamer) {}
461};
462
Karl Wibergcefc4652018-05-23 23:20:38 +0200463} // namespace webrtc_logging_impl
464
465// Direct use of this class is deprecated; please use the logging macros
466// instead.
467// TODO(bugs.webrtc.org/9278): Move this class to an unnamed namespace in the
468// .cc file.
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200469class LogMessage {
470 public:
Karl Wiberg1ffb3742018-05-04 15:04:48 +0200471 // Same as the above, but using a compile-time constant for the logging
472 // severity. This saves space at the call site, since passing an empty struct
473 // is generally the same as not passing an argument at all.
474 template <LoggingSeverity S>
475 RTC_NO_INLINE LogMessage(const char* file,
476 int line,
477 std::integral_constant<LoggingSeverity, S>)
478 : LogMessage(file, line, S) {}
479
Artem Titov6a4a1462019-11-26 16:24:46 +0100480#if RTC_LOG_ENABLED()
481 LogMessage(const char* file, int line, LoggingSeverity sev);
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200482 LogMessage(const char* file,
483 int line,
484 LoggingSeverity sev,
Karl Wibergab4f1c12018-05-04 10:42:28 +0200485 LogErrorContext err_ctx,
486 int err);
Tommie51a0a82018-02-27 15:30:29 +0100487#if defined(WEBRTC_ANDROID)
488 LogMessage(const char* file, int line, LoggingSeverity sev, const char* tag);
489#endif
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200490 ~LogMessage();
491
Byoungchan Lee14af7622022-01-12 05:24:58 +0900492 LogMessage(const LogMessage&) = delete;
493 LogMessage& operator=(const LogMessage&) = delete;
494
Karl Wibergcefc4652018-05-23 23:20:38 +0200495 void AddTag(const char* tag);
Jonas Olssond8c50782018-09-07 11:21:28 +0200496 rtc::StringBuilder& stream();
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200497 // Returns the time at which this function was called for the first time.
498 // The time will be used as the logging start time.
499 // If this is not called externally, the LogMessage ctor also calls it, in
500 // which case the logging start time will be the time of the first LogMessage
501 // instance is created.
502 static int64_t LogStartTime();
Artem Titov96e3b992021-07-26 16:03:14 +0200503 // Returns the wall clock equivalent of `LogStartTime`, in seconds from the
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200504 // epoch.
505 static uint32_t WallClockStartTime();
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200506 // LogThreads: Display the thread identifier of the current thread
507 static void LogThreads(bool on = true);
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200508 // LogTimestamps: Display the elapsed time of the program
509 static void LogTimestamps(bool on = true);
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200510 // These are the available logging channels
511 // Debug: Debug console on Windows, otherwise stderr
512 static void LogToDebug(LoggingSeverity min_sev);
Jonas Olsson2b6f1352018-02-15 11:57:03 +0100513 static LoggingSeverity GetLogToDebug();
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200514 // Sets whether logs will be directed to stderr in debug mode.
515 static void SetLogToStderr(bool log_to_stderr);
Danil Chapovalovb9f69022019-10-21 09:19:10 +0200516 // Stream: Any non-blocking stream interface.
Artem Titov96e3b992021-07-26 16:03:14 +0200517 // Installs the `stream` to collect logs with severtiy `min_sev` or higher.
518 // `stream` must live until deinstalled by RemoveLogToStream.
519 // If `stream` is the first stream added to the system, we might miss some
Markus Handell531bd0f2020-07-08 10:58:19 +0200520 // early concurrent log statement happening from another thread happening near
521 // this instant.
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200522 static void AddLogToStream(LogSink* stream, LoggingSeverity min_sev);
Markus Handell531bd0f2020-07-08 10:58:19 +0200523 // Removes the specified stream, without destroying it. When the method
Artem Titov96e3b992021-07-26 16:03:14 +0200524 // has completed, it's guaranteed that `stream` will receive no more logging
Markus Handell531bd0f2020-07-08 10:58:19 +0200525 // calls.
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200526 static void RemoveLogToStream(LogSink* stream);
Danil Chapovalovb9f69022019-10-21 09:19:10 +0200527 // Returns the severity for the specified stream, of if none is specified,
528 // the minimum stream severity.
529 static int GetLogToStream(LogSink* stream = nullptr);
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200530 // Testing against MinLogSeverity allows code to avoid potentially expensive
531 // logging operations by pre-checking the logging level.
Jonas Olsson2b6f1352018-02-15 11:57:03 +0100532 static int GetMinLogSeverity();
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200533 // Parses the provided parameter stream to configure the options above.
534 // Useful for configuring logging from the command line.
Ali Tofigh2ab914c2022-04-13 12:55:15 +0200535 static void ConfigureLogging(absl::string_view params);
Artem Titov96e3b992021-07-26 16:03:14 +0200536 // Checks the current global debug severity and if the `streams_` collection
537 // is empty. If `severity` is smaller than the global severity and if the
538 // `streams_` collection is empty, the LogMessage will be considered a noop
Jonas Olssond8c50782018-09-07 11:21:28 +0200539 // LogMessage.
540 static bool IsNoop(LoggingSeverity severity);
Karl Wibergdd7df5c2020-09-22 11:07:53 +0200541 // Version of IsNoop that uses fewer instructions at the call site, since the
542 // caller doesn't have to pass an argument.
543 template <LoggingSeverity S>
544 RTC_NO_INLINE static bool IsNoop() {
545 return IsNoop(S);
546 }
Artem Titov6a4a1462019-11-26 16:24:46 +0100547#else
548 // Next methods do nothing; no one will call these functions.
549 LogMessage(const char* file, int line, LoggingSeverity sev) {}
550 LogMessage(const char* file,
551 int line,
552 LoggingSeverity sev,
553 LogErrorContext err_ctx,
554 int err) {}
555#if defined(WEBRTC_ANDROID)
556 LogMessage(const char* file, int line, LoggingSeverity sev, const char* tag) {
557 }
558#endif
Artem Titov6a4a1462019-11-26 16:24:46 +0100559 ~LogMessage() = default;
560
561 inline void AddTag(const char* tag) {}
562 inline rtc::StringBuilder& stream() { return print_stream_; }
563 inline static int64_t LogStartTime() { return 0; }
564 inline static uint32_t WallClockStartTime() { return 0; }
565 inline static void LogThreads(bool on = true) {}
566 inline static void LogTimestamps(bool on = true) {}
567 inline static void LogToDebug(LoggingSeverity min_sev) {}
568 inline static LoggingSeverity GetLogToDebug() {
569 return LoggingSeverity::LS_INFO;
570 }
571 inline static void SetLogToStderr(bool log_to_stderr) {}
572 inline static void AddLogToStream(LogSink* stream, LoggingSeverity min_sev) {}
573 inline static void RemoveLogToStream(LogSink* stream) {}
574 inline static int GetLogToStream(LogSink* stream = nullptr) { return 0; }
575 inline static int GetMinLogSeverity() { return 0; }
Ali Tofigh2ab914c2022-04-13 12:55:15 +0200576 inline static void ConfigureLogging(absl::string_view params) {}
Karl Wiberg0e884382020-09-22 09:34:45 +0200577 static constexpr bool IsNoop(LoggingSeverity severity) { return true; }
Karl Wibergdd7df5c2020-09-22 11:07:53 +0200578 template <LoggingSeverity S>
579 static constexpr bool IsNoop() {
580 return IsNoop(S);
581 }
Artem Titov6a4a1462019-11-26 16:24:46 +0100582#endif // RTC_LOG_ENABLED()
Jonas Olssond8c50782018-09-07 11:21:28 +0200583
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200584 private:
Tommifef05002018-02-27 13:51:08 +0100585 friend class LogMessageForTesting;
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200586
Artem Titov6a4a1462019-11-26 16:24:46 +0100587#if RTC_LOG_ENABLED()
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200588 // Updates min_sev_ appropriately when debug sinks change.
589 static void UpdateMinLogSeverity();
590
Mirko Bonadei96191f82022-08-03 08:12:33 +0000591 // This writes out the actual log messages.
592 static void OutputToDebug(const LogLineRef& log_line_ref);
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200593
Tommifef05002018-02-27 13:51:08 +0100594 // Called from the dtor (or from a test) to append optional extra error
595 // information to the log stream and a newline character.
596 void FinishPrintStream();
597
Mirko Bonadei96191f82022-08-03 08:12:33 +0000598 LogLineRef log_line_;
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200599
600 // String data generated in the constructor, that should be appended to
601 // the message before output.
602 std::string extra_;
603
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200604 // The output streams and their associated severities
Danil Chapovalovb9f69022019-10-21 09:19:10 +0200605 static LogSink* streams_;
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200606
Artem Titov96e3b992021-07-26 16:03:14 +0200607 // Holds true with high probability if `streams_` is empty, false with high
Markus Handellce1ff6f2020-07-08 08:52:48 +0200608 // probability otherwise. Operated on with std::memory_order_relaxed because
Markus Handell531bd0f2020-07-08 10:58:19 +0200609 // it's ok to lose or log some additional statements near the instant streams
Markus Handellce1ff6f2020-07-08 08:52:48 +0200610 // are added/removed.
611 static std::atomic<bool> streams_empty_;
612
Mirko Bonadei96191f82022-08-03 08:12:33 +0000613 // Flags for formatting options and their potential values.
614 static bool log_thread_;
615 static bool log_timestamp_;
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200616
617 // Determines if logs will be directed to stderr in debug mode.
618 static bool log_to_stderr_;
Artem Titov6a4a1462019-11-26 16:24:46 +0100619#else // RTC_LOG_ENABLED()
620 // Next methods do nothing; no one will call these functions.
621 inline static void UpdateMinLogSeverity() {}
622#if defined(WEBRTC_ANDROID)
Mirko Bonadei96191f82022-08-03 08:12:33 +0000623 inline static void OutputToDebug(absl::string_view filename,
624 int line,
625 absl::string_view msg,
Artem Titov6a4a1462019-11-26 16:24:46 +0100626 LoggingSeverity severity,
627 const char* tag) {}
628#else
Mirko Bonadei96191f82022-08-03 08:12:33 +0000629 inline static void OutputToDebug(absl::string_view filename,
630 int line,
631 absl::string_view msg,
Artem Titov6a4a1462019-11-26 16:24:46 +0100632 LoggingSeverity severity) {}
633#endif // defined(WEBRTC_ANDROID)
634 inline void FinishPrintStream() {}
635#endif // RTC_LOG_ENABLED()
636
637 // The stringbuilder that buffers the formatted message before output
638 rtc::StringBuilder print_stream_;
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200639};
640
641//////////////////////////////////////////////////////////////////////
642// Logging Helpers
643//////////////////////////////////////////////////////////////////////
644
Karl Wibergdd7df5c2020-09-22 11:07:53 +0200645#define RTC_LOG_FILE_LINE(sev, file, line) \
646 ::rtc::webrtc_logging_impl::LogCall() & \
647 ::rtc::webrtc_logging_impl::LogStreamer<>() \
648 << ::rtc::webrtc_logging_impl::LogMetadata(file, line, sev)
Jonas Olsson8a7916b2018-09-06 09:50:23 +0200649
Karl Wibergdd7df5c2020-09-22 11:07:53 +0200650#define RTC_LOG(sev) \
651 !rtc::LogMessage::IsNoop<::rtc::sev>() && \
652 RTC_LOG_FILE_LINE(::rtc::sev, __FILE__, __LINE__)
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200653
Per Kjellander4d419132022-09-30 12:50:41 +0200654#define RTC_LOG_IF(sev, condition) \
655 !rtc::LogMessage::IsNoop<::rtc::sev>() && (condition) && \
656 RTC_LOG_FILE_LINE(::rtc::sev, __FILE__, __LINE__)
657
Karl Wibergcefc4652018-05-23 23:20:38 +0200658// The _V version is for when a variable is passed in.
Karl Wibergdd7df5c2020-09-22 11:07:53 +0200659#define RTC_LOG_V(sev) \
660 !rtc::LogMessage::IsNoop(sev) && RTC_LOG_FILE_LINE(sev, __FILE__, __LINE__)
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200661
662// The _F version prefixes the message with the current function name.
663#if (defined(__GNUC__) && !defined(NDEBUG)) || defined(WANT_PRETTY_LOG_F)
Mirko Bonadei8ed8e562017-10-27 09:43:53 +0200664#define RTC_LOG_F(sev) RTC_LOG(sev) << __PRETTY_FUNCTION__ << ": "
Per Kjellander4d419132022-09-30 12:50:41 +0200665#define RTC_LOG_IF_F(sev, condition) \
666 RTC_LOG_IF(sev, condition) << __PRETTY_FUNCTION__ << ": "
Yves Gerey665174f2018-06-19 15:03:05 +0200667#define RTC_LOG_T_F(sev) \
668 RTC_LOG(sev) << this << ": " << __PRETTY_FUNCTION__ << ": "
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200669#else
Mirko Bonadei8ed8e562017-10-27 09:43:53 +0200670#define RTC_LOG_F(sev) RTC_LOG(sev) << __FUNCTION__ << ": "
Per Kjellander4d419132022-09-30 12:50:41 +0200671#define RTC_LOG_IF_F(sev, condition) \
672 RTC_LOG_IF(sev, condition) << __FUNCTION__ << ": "
Patrik Höglundc2962552017-11-17 13:40:22 +0000673#define RTC_LOG_T_F(sev) RTC_LOG(sev) << this << ": " << __FUNCTION__ << ": "
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200674#endif
675
Jiawei Ou14e5f0b2020-03-04 13:38:02 -0800676#define RTC_LOG_CHECK_LEVEL(sev) ::rtc::LogCheckLevel(::rtc::sev)
677#define RTC_LOG_CHECK_LEVEL_V(sev) ::rtc::LogCheckLevel(sev)
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200678
679inline bool LogCheckLevel(LoggingSeverity sev) {
680 return (LogMessage::GetMinLogSeverity() <= sev);
681}
682
Karl Wiberg92e37962020-09-22 13:22:20 +0200683#define RTC_LOG_E(sev, ctx, err) \
684 !rtc::LogMessage::IsNoop<::rtc::sev>() && \
685 ::rtc::webrtc_logging_impl::LogCall() & \
686 ::rtc::webrtc_logging_impl::LogStreamer<>() \
687 << ::rtc::webrtc_logging_impl::LogMetadataErr { \
688 {__FILE__, __LINE__, ::rtc::sev}, ::rtc::ERRCTX_##ctx, (err) \
Jonas Olssona4d87372019-07-05 19:08:33 +0200689 }
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200690
Mirko Bonadei8ed8e562017-10-27 09:43:53 +0200691#define RTC_LOG_T(sev) RTC_LOG(sev) << this << ": "
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200692
Yves Gerey665174f2018-06-19 15:03:05 +0200693#define RTC_LOG_ERRNO_EX(sev, err) RTC_LOG_E(sev, ERRNO, err)
694#define RTC_LOG_ERRNO(sev) RTC_LOG_ERRNO_EX(sev, errno)
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200695
696#if defined(WEBRTC_WIN)
Yves Gerey665174f2018-06-19 15:03:05 +0200697#define RTC_LOG_GLE_EX(sev, err) RTC_LOG_E(sev, HRESULT, err)
Karl Wibergcefc4652018-05-23 23:20:38 +0200698#define RTC_LOG_GLE(sev) RTC_LOG_GLE_EX(sev, static_cast<int>(GetLastError()))
Yves Gerey665174f2018-06-19 15:03:05 +0200699#define RTC_LOG_ERR_EX(sev, err) RTC_LOG_GLE_EX(sev, err)
700#define RTC_LOG_ERR(sev) RTC_LOG_GLE(sev)
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200701#elif defined(__native_client__) && __native_client__
Yves Gerey665174f2018-06-19 15:03:05 +0200702#define RTC_LOG_ERR_EX(sev, err) RTC_LOG(sev)
703#define RTC_LOG_ERR(sev) RTC_LOG(sev)
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200704#elif defined(WEBRTC_POSIX)
Yves Gerey665174f2018-06-19 15:03:05 +0200705#define RTC_LOG_ERR_EX(sev, err) RTC_LOG_ERRNO_EX(sev, err)
706#define RTC_LOG_ERR(sev) RTC_LOG_ERRNO(sev)
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200707#endif // WEBRTC_WIN
708
Karl Wibergcefc4652018-05-23 23:20:38 +0200709#ifdef WEBRTC_ANDROID
710
711namespace webrtc_logging_impl {
712// TODO(kwiberg): Replace these with absl::string_view.
Yves Gerey665174f2018-06-19 15:03:05 +0200713inline const char* AdaptString(const char* str) {
714 return str;
715}
716inline const char* AdaptString(const std::string& str) {
717 return str.c_str();
718}
Karl Wibergcefc4652018-05-23 23:20:38 +0200719} // namespace webrtc_logging_impl
720
Karl Wiberg92e37962020-09-22 13:22:20 +0200721#define RTC_LOG_TAG(sev, tag) \
722 !rtc::LogMessage::IsNoop(sev) && \
723 ::rtc::webrtc_logging_impl::LogCall() & \
724 ::rtc::webrtc_logging_impl::LogStreamer<>() \
725 << ::rtc::webrtc_logging_impl::LogMetadataTag { \
726 sev, ::rtc::webrtc_logging_impl::AdaptString(tag) \
Jonas Olssona4d87372019-07-05 19:08:33 +0200727 }
Karl Wibergcefc4652018-05-23 23:20:38 +0200728
Tommie51a0a82018-02-27 15:30:29 +0100729#else
Karl Wibergcefc4652018-05-23 23:20:38 +0200730
Tommie51a0a82018-02-27 15:30:29 +0100731// DEPRECATED. This macro is only intended for Android.
Karl Wibergcefc4652018-05-23 23:20:38 +0200732#define RTC_LOG_TAG(sev, tag) RTC_LOG_V(sev)
733
Tommie51a0a82018-02-27 15:30:29 +0100734#endif
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200735
Fredrik Solenbergb3d7cac2017-11-17 15:22:37 +0100736// The RTC_DLOG macros are equivalent to their RTC_LOG counterparts except that
737// they only generate code in debug builds.
738#if RTC_DLOG_IS_ON
739#define RTC_DLOG(sev) RTC_LOG(sev)
Per Kjellander4d419132022-09-30 12:50:41 +0200740#define RTC_DLOG_IF(sev, condition) RTC_LOG_IF(sev, condition)
Fredrik Solenbergb3d7cac2017-11-17 15:22:37 +0100741#define RTC_DLOG_V(sev) RTC_LOG_V(sev)
742#define RTC_DLOG_F(sev) RTC_LOG_F(sev)
Per Kjellander4d419132022-09-30 12:50:41 +0200743#define RTC_DLOG_IF_F(sev, condition) RTC_LOG_IF_F(sev, condition)
Fredrik Solenbergb3d7cac2017-11-17 15:22:37 +0100744#else
Mirko Bonadeif1df04b2020-03-23 19:53:23 +0100745#define RTC_DLOG_EAT_STREAM_PARAMS() \
746 while (false) \
747 ::rtc::webrtc_logging_impl::LogMessageVoidify() & \
748 (::rtc::webrtc_logging_impl::LogStreamer<>())
Karl Wibergcefc4652018-05-23 23:20:38 +0200749#define RTC_DLOG(sev) RTC_DLOG_EAT_STREAM_PARAMS()
Per Kjellander4d419132022-09-30 12:50:41 +0200750#define RTC_DLOG_IF(sev, condition) RTC_DLOG_EAT_STREAM_PARAMS()
Karl Wibergcefc4652018-05-23 23:20:38 +0200751#define RTC_DLOG_V(sev) RTC_DLOG_EAT_STREAM_PARAMS()
752#define RTC_DLOG_F(sev) RTC_DLOG_EAT_STREAM_PARAMS()
Per Kjellander4d419132022-09-30 12:50:41 +0200753#define RTC_DLOG_IF_F(sev, condition) RTC_DLOG_EAT_STREAM_PARAMS()
Fredrik Solenbergb3d7cac2017-11-17 15:22:37 +0100754#endif
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200755
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200756} // namespace rtc
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000757
Mirko Bonadei92ea95e2017-09-15 06:47:31 +0200758#endif // RTC_BASE_LOGGING_H_