1 /*
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
11 // RTC_LOG(...) an ostream target that can be used to send formatted
12 // output to a variety of logging targets, such as debugger console, stderr,
13 // or any LogSink.
14 // The severity level passed as the first argument to the logging
15 // functions is used as a filter, to limit the verbosity of the logging.
16 // Static members of LogMessage documented below are used to control the
17 // verbosity and target of the output.
18 // There are several variations on the RTC_LOG macro which facilitate logging
19 // of common error conditions, detailed below.
20
21 // RTC_LOG(sev) logs the given stream at severity "sev", which must be a
22 // compile-time constant of the LoggingSeverity type, without the namespace
23 // prefix.
24 // RTC_LOG_IF(sev, condition) logs the given stream at severitye "sev" if
25 // "condition" is true.
26 // 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.
29 // RTC_LOG_IF_F(sev, condition), Like RTC_LOG_IF(), but includes the name of
30 // the current function.
31 // 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.
33 // RTC_LOG_GLE(sev [, mod]) attempt to add a string description of the
34 // HRESULT returned by GetLastError.
35 // RTC_LOG_ERRNO(sev) attempts to add a string description of an errno-derived
36 // error. errno and associated facilities exist on both Windows and POSIX,
37 // but on Windows they only apply to the C/C++ runtime.
38 // RTC_LOG_ERR(sev) is an alias for the platform's normal error system, i.e.
39 // _GLE on Windows and _ERRNO on POSIX.
40 // (The above three also all have _EX versions that let you specify the error
41 // code, rather than using the last one.)
42 // RTC_LOG_E(sev, ctx, err, ...) logs a detailed error interpreted using the
43 // specified context.
44 // 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.
47
48 #ifndef RTC_BASE_LOGGING_H_
49 #define RTC_BASE_LOGGING_H_
50
51 #include <errno.h>
52
53 #include <atomic>
54 #include <sstream> // no-presubmit-check TODO(webrtc:8982)
55 #include <string>
56 #include <type_traits>
57 #include <utility>
58
59 #include "absl/base/attributes.h"
60 #include "absl/meta/type_traits.h"
61 #include "absl/strings/string_view.h"
62 #include "absl/types/optional.h"
63 #include "api/units/timestamp.h"
64 #include "rtc_base/platform_thread_types.h"
65 #include "rtc_base/strings/string_builder.h"
66 #include "rtc_base/system/inline.h"
67
68 #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
74 #if defined(RTC_DISABLE_LOGGING)
75 #define RTC_LOG_ENABLED() 0
76 #else
77 #define RTC_LOG_ENABLED() 1
78 #endif
79
80 namespace rtc {
81
82 //////////////////////////////////////////////////////////////////////
83 // The meanings of the levels are:
84 // 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.
91 enum LoggingSeverity {
92 LS_VERBOSE,
93 LS_INFO,
94 LS_WARNING,
95 LS_ERROR,
96 LS_NONE,
97 };
98
99 // LogErrorContext assists in interpreting the meaning of an error value.
100 enum LogErrorContext {
101 ERRCTX_NONE,
102 ERRCTX_ERRNO, // System-local errno
103 ERRCTX_HRESULT, // Windows HRESULT
104
105 // Abbreviations for LOG_E macro
106 ERRCTX_EN = ERRCTX_ERRNO, // LOG_E(sev, EN, x)
107 ERRCTX_HR = ERRCTX_HRESULT, // LOG_E(sev, HR, x)
108 };
109
110 class LogMessage;
111
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.
116 class LogLineRef {
117 public:
message()118 absl::string_view message() const { return message_; }
filename()119 absl::string_view filename() const { return filename_; }
line()120 int line() const { return line_; }
thread_id()121 absl::optional<PlatformThreadId> thread_id() const { return thread_id_; }
timestamp()122 webrtc::Timestamp timestamp() const { return timestamp_; }
tag()123 absl::string_view tag() const { return tag_; }
severity()124 LoggingSeverity severity() const { return severity_; }
125
126 #if RTC_LOG_ENABLED()
127 std::string DefaultLogLine() const;
128 #else
DefaultLogLine()129 std::string DefaultLogLine() const { return ""; }
130 #endif
131
132 private:
133 friend class LogMessage;
set_message(std::string message)134 void set_message(std::string message) { message_ = std::move(message); }
set_filename(absl::string_view filename)135 void set_filename(absl::string_view filename) { filename_ = filename; }
set_line(int line)136 void set_line(int line) { line_ = line; }
set_thread_id(absl::optional<PlatformThreadId> thread_id)137 void set_thread_id(absl::optional<PlatformThreadId> thread_id) {
138 thread_id_ = thread_id;
139 }
set_timestamp(webrtc::Timestamp timestamp)140 void set_timestamp(webrtc::Timestamp timestamp) { timestamp_ = timestamp; }
set_tag(absl::string_view tag)141 void set_tag(absl::string_view tag) { tag_ = tag; }
set_severity(LoggingSeverity severity)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
155 // Virtual sink interface that can receive log messages.
156 class LogSink {
157 public:
LogSink()158 LogSink() {}
~LogSink()159 virtual ~LogSink() {}
160 virtual void OnLogMessage(const std::string& msg,
161 LoggingSeverity severity,
162 const char* tag);
163 virtual void OnLogMessage(const std::string& message,
164 LoggingSeverity severity);
165 virtual void OnLogMessage(const std::string& message) = 0;
166
167 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);
173 virtual void OnLogMessage(const LogLineRef& line);
174
175 private:
176 friend class ::rtc::LogMessage;
177 #if RTC_LOG_ENABLED()
178 // Members for LogMessage class to keep linked list of the registered sinks.
179 LogSink* next_ = nullptr;
180 LoggingSeverity min_severity_;
181 #endif
182 };
183
184 namespace webrtc_logging_impl {
185
186 class LogMetadata {
187 public:
LogMetadata(const char * file,int line,LoggingSeverity severity)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
File()193 const char* File() const { return file_; }
Line()194 int Line() const { return line_and_sev_ >> 3; }
Severity()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 };
208 static_assert(std::is_trivial<LogMetadata>::value, "");
209
210 struct LogMetadataErr {
211 LogMetadata meta;
212 LogErrorContext err_ctx;
213 int err;
214 };
215
216 #ifdef WEBRTC_ANDROID
217 struct LogMetadataTag {
218 LoggingSeverity severity;
219 const char* tag;
220 };
221 #endif
222
223 enum 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,
235 kStringView,
236 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.
246 template <LogArgType N, typename T>
247 struct Val {
TypeVal248 static constexpr LogArgType Type() { return N; }
GetValVal249 T GetVal() const { return val; }
250 T val;
251 };
252
253 // 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.)
256 struct ToStringVal {
TypeToStringVal257 static constexpr LogArgType Type() { return LogArgType::kStdString; }
GetValToStringVal258 const std::string* GetVal() const { return &val; }
259 std::string val;
260 };
261
MakeVal(int x)262 inline Val<LogArgType::kInt, int> MakeVal(int x) {
263 return {x};
264 }
MakeVal(long x)265 inline Val<LogArgType::kLong, long> MakeVal(long x) {
266 return {x};
267 }
MakeVal(long long x)268 inline Val<LogArgType::kLongLong, long long> MakeVal(long long x) {
269 return {x};
270 }
MakeVal(unsigned int x)271 inline Val<LogArgType::kUInt, unsigned int> MakeVal(unsigned int x) {
272 return {x};
273 }
MakeVal(unsigned long x)274 inline Val<LogArgType::kULong, unsigned long> MakeVal(unsigned long x) {
275 return {x};
276 }
MakeVal(unsigned long long x)277 inline Val<LogArgType::kULongLong, unsigned long long> MakeVal(
278 unsigned long long x) {
279 return {x};
280 }
281
MakeVal(double x)282 inline Val<LogArgType::kDouble, double> MakeVal(double x) {
283 return {x};
284 }
MakeVal(long double x)285 inline Val<LogArgType::kLongDouble, long double> MakeVal(long double x) {
286 return {x};
287 }
288
MakeVal(const char * x)289 inline Val<LogArgType::kCharP, const char*> MakeVal(const char* x) {
290 return {x};
291 }
MakeVal(const std::string & x)292 inline Val<LogArgType::kStdString, const std::string*> MakeVal(
293 const std::string& x) {
294 return {&x};
295 }
MakeVal(const absl::string_view & x)296 inline Val<LogArgType::kStringView, const absl::string_view*> MakeVal(
297 const absl::string_view& x) {
298 return {&x};
299 }
300
MakeVal(const void * x)301 inline Val<LogArgType::kVoidP, const void*> MakeVal(const void* x) {
302 return {x};
303 }
304
MakeVal(const LogMetadata & x)305 inline Val<LogArgType::kLogMetadata, LogMetadata> MakeVal(
306 const LogMetadata& x) {
307 return {x};
308 }
MakeVal(const LogMetadataErr & x)309 inline Val<LogArgType::kLogMetadataErr, LogMetadataErr> MakeVal(
310 const LogMetadataErr& x) {
311 return {x};
312 }
313
314 // The enum class types are not implicitly convertible to arithmetic types.
315 template <typename T,
316 absl::enable_if_t<std::is_enum<T>::value &&
317 !std::is_arithmetic<T>::value>* = nullptr>
decltype(MakeVal (std::declval<absl::underlying_type_t<T>> ()))318 inline decltype(MakeVal(std::declval<absl::underlying_type_t<T>>())) MakeVal(
319 T x) {
320 return {static_cast<absl::underlying_type_t<T>>(x)};
321 }
322
323 #ifdef WEBRTC_ANDROID
MakeVal(const LogMetadataTag & x)324 inline Val<LogArgType::kLogMetadataTag, LogMetadataTag> MakeVal(
325 const LogMetadataTag& x) {
326 return {x};
327 }
328 #endif
329
330 template <typename T, class = void>
331 struct has_to_log_string : std::false_type {};
332 template <typename T>
333 struct 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
338 template <typename T, absl::enable_if_t<has_to_log_string<T>::value>* = nullptr>
339 ToStringVal MakeVal(const T& x) {
340 return {ToLogString(x)};
341 }
342
343 // 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.
346 template <
347 typename T,
348 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 &&
353 #ifdef WEBRTC_ANDROID
354 !std::is_same<T1, LogMetadataTag>::value &&
355 #endif
356 !std::is_same<T1, LogMetadataErr>::value>* = nullptr>
357 ToStringVal MakeVal(const T& x) {
358 std::ostringstream os; // no-presubmit-check TODO(webrtc:8982)
359 os << x;
360 return {os.str()};
361 }
362
363 #if RTC_LOG_ENABLED()
364 void Log(const LogArgType* fmt, ...);
365 #else
366 inline void Log(const LogArgType* fmt, ...) {
367 // Do nothing, shouldn't be invoked
368 }
369 #endif
370
371 // Ephemeral type that represents the result of the logging << operator.
372 template <typename... Ts>
373 class LogStreamer;
374
375 // Base case: Before the first << argument.
376 template <>
377 class LogStreamer<> final {
378 public:
379 template <typename U,
380 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);
385 }
386
387 template <typename U,
388 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);
393 }
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`.
404 template <typename T, typename... Ts>
405 class LogStreamer<T, Ts...> final {
406 public:
407 RTC_FORCE_INLINE LogStreamer(T arg, const LogStreamer<Ts...>* prior)
408 : arg_(arg), prior_(prior) {}
409
410 template <typename U,
411 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);
416 }
417
418 template <typename U,
419 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);
424 }
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
439 class LogCall final {
440 public:
441 // This can be any binary operator with precedence lower than <<.
442 // We return bool here to be able properly remove logging if
443 // RTC_DISABLE_LOGGING is defined.
444 template <typename... Ts>
445 RTC_FORCE_INLINE bool operator&(const LogStreamer<Ts...>& streamer) {
446 streamer.Call();
447 return true;
448 }
449 };
450
451 // 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".
454 class 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
463 } // 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.
469 class LogMessage {
470 public:
471 // 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
480 #if RTC_LOG_ENABLED()
481 LogMessage(const char* file, int line, LoggingSeverity sev);
482 LogMessage(const char* file,
483 int line,
484 LoggingSeverity sev,
485 LogErrorContext err_ctx,
486 int err);
487 #if defined(WEBRTC_ANDROID)
488 LogMessage(const char* file, int line, LoggingSeverity sev, const char* tag);
489 #endif
490 ~LogMessage();
491
492 LogMessage(const LogMessage&) = delete;
493 LogMessage& operator=(const LogMessage&) = delete;
494
495 void AddTag(const char* tag);
496 rtc::StringBuilder& stream();
497 // 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();
503 // Returns the wall clock equivalent of `LogStartTime`, in seconds from the
504 // epoch.
505 static uint32_t WallClockStartTime();
506 // LogThreads: Display the thread identifier of the current thread
507 static void LogThreads(bool on = true);
508 // LogTimestamps: Display the elapsed time of the program
509 static void LogTimestamps(bool on = true);
510 // These are the available logging channels
511 // Debug: Debug console on Windows, otherwise stderr
512 static void LogToDebug(LoggingSeverity min_sev);
513 static LoggingSeverity GetLogToDebug();
514 // Sets whether logs will be directed to stderr in debug mode.
515 static void SetLogToStderr(bool log_to_stderr);
516 // Stream: Any non-blocking stream interface.
517 // 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
520 // early concurrent log statement happening from another thread happening near
521 // this instant.
522 static void AddLogToStream(LogSink* stream, LoggingSeverity min_sev);
523 // Removes the specified stream, without destroying it. When the method
524 // has completed, it's guaranteed that `stream` will receive no more logging
525 // calls.
526 static void RemoveLogToStream(LogSink* stream);
527 // Returns the severity for the specified stream, of if none is specified,
528 // the minimum stream severity.
529 static int GetLogToStream(LogSink* stream = nullptr);
530 // Testing against MinLogSeverity allows code to avoid potentially expensive
531 // logging operations by pre-checking the logging level.
532 static int GetMinLogSeverity();
533 // Parses the provided parameter stream to configure the options above.
534 // Useful for configuring logging from the command line.
535 static void ConfigureLogging(absl::string_view params);
536 // 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
539 // LogMessage.
540 static bool IsNoop(LoggingSeverity severity);
541 // 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 }
547 #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
559 ~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; }
576 inline static void ConfigureLogging(absl::string_view params) {}
577 static constexpr bool IsNoop(LoggingSeverity severity) { return true; }
578 template <LoggingSeverity S>
579 static constexpr bool IsNoop() {
580 return IsNoop(S);
581 }
582 #endif // RTC_LOG_ENABLED()
583
584 private:
585 friend class LogMessageForTesting;
586
587 #if RTC_LOG_ENABLED()
588 // Updates min_sev_ appropriately when debug sinks change.
589 static void UpdateMinLogSeverity();
590
591 // This writes out the actual log messages.
592 static void OutputToDebug(const LogLineRef& log_line_ref);
593
594 // 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
598 LogLineRef log_line_;
599
600 // String data generated in the constructor, that should be appended to
601 // the message before output.
602 std::string extra_;
603
604 // The output streams and their associated severities
605 static LogSink* streams_;
606
607 // Holds true with high probability if `streams_` is empty, false with high
608 // probability otherwise. Operated on with std::memory_order_relaxed because
609 // it's ok to lose or log some additional statements near the instant streams
610 // are added/removed.
611 static std::atomic<bool> streams_empty_;
612
613 // Flags for formatting options and their potential values.
614 static bool log_thread_;
615 static bool log_timestamp_;
616
617 // Determines if logs will be directed to stderr in debug mode.
618 static bool log_to_stderr_;
619 #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)
623 inline static void OutputToDebug(absl::string_view filename,
624 int line,
625 absl::string_view msg,
626 LoggingSeverity severity,
627 const char* tag) {}
628 #else
629 inline static void OutputToDebug(absl::string_view filename,
630 int line,
631 absl::string_view msg,
632 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_;
639 };
640
641 //////////////////////////////////////////////////////////////////////
642 // Logging Helpers
643 //////////////////////////////////////////////////////////////////////
644
645 #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)
649
650 #define RTC_LOG(sev) \
651 !rtc::LogMessage::IsNoop<::rtc::sev>() && \
652 RTC_LOG_FILE_LINE(::rtc::sev, __FILE__, __LINE__)
653
654 #define RTC_LOG_IF(sev, condition) \
655 !rtc::LogMessage::IsNoop<::rtc::sev>() && (condition) && \
656 RTC_LOG_FILE_LINE(::rtc::sev, __FILE__, __LINE__)
657
658 // The _V version is for when a variable is passed in.
659 #define RTC_LOG_V(sev) \
660 !rtc::LogMessage::IsNoop(sev) && RTC_LOG_FILE_LINE(sev, __FILE__, __LINE__)
661
662 // The _F version prefixes the message with the current function name.
663 #if (defined(__GNUC__) && !defined(NDEBUG)) || defined(WANT_PRETTY_LOG_F)
664 #define RTC_LOG_F(sev) RTC_LOG(sev) << __PRETTY_FUNCTION__ << ": "
665 #define RTC_LOG_IF_F(sev, condition) \
666 RTC_LOG_IF(sev, condition) << __PRETTY_FUNCTION__ << ": "
667 #define RTC_LOG_T_F(sev) \
668 RTC_LOG(sev) << this << ": " << __PRETTY_FUNCTION__ << ": "
669 #else
670 #define RTC_LOG_F(sev) RTC_LOG(sev) << __FUNCTION__ << ": "
671 #define RTC_LOG_IF_F(sev, condition) \
672 RTC_LOG_IF(sev, condition) << __FUNCTION__ << ": "
673 #define RTC_LOG_T_F(sev) RTC_LOG(sev) << this << ": " << __FUNCTION__ << ": "
674 #endif
675
676 #define RTC_LOG_CHECK_LEVEL(sev) ::rtc::LogCheckLevel(::rtc::sev)
677 #define RTC_LOG_CHECK_LEVEL_V(sev) ::rtc::LogCheckLevel(sev)
678
679 inline bool LogCheckLevel(LoggingSeverity sev) {
680 return (LogMessage::GetMinLogSeverity() <= sev);
681 }
682
683 #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) \
689 }
690
691 #define RTC_LOG_T(sev) RTC_LOG(sev) << this << ": "
692
693 #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)
695
696 #if defined(WEBRTC_WIN)
697 #define RTC_LOG_GLE_EX(sev, err) RTC_LOG_E(sev, HRESULT, err)
698 #define RTC_LOG_GLE(sev) RTC_LOG_GLE_EX(sev, static_cast<int>(GetLastError()))
699 #define RTC_LOG_ERR_EX(sev, err) RTC_LOG_GLE_EX(sev, err)
700 #define RTC_LOG_ERR(sev) RTC_LOG_GLE(sev)
701 #elif defined(__native_client__) && __native_client__
702 #define RTC_LOG_ERR_EX(sev, err) RTC_LOG(sev)
703 #define RTC_LOG_ERR(sev) RTC_LOG(sev)
704 #elif defined(WEBRTC_POSIX)
705 #define RTC_LOG_ERR_EX(sev, err) RTC_LOG_ERRNO_EX(sev, err)
706 #define RTC_LOG_ERR(sev) RTC_LOG_ERRNO(sev)
707 #endif // WEBRTC_WIN
708
709 #ifdef WEBRTC_ANDROID
710
711 namespace webrtc_logging_impl {
712 // TODO(kwiberg): Replace these with absl::string_view.
713 inline const char* AdaptString(const char* str) {
714 return str;
715 }
716 inline const char* AdaptString(const std::string& str) {
717 return str.c_str();
718 }
719 } // namespace webrtc_logging_impl
720
721 #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) \
727 }
728
729 #else
730
731 // DEPRECATED. This macro is only intended for Android.
732 #define RTC_LOG_TAG(sev, tag) RTC_LOG_V(sev)
733
734 #endif
735
736 // 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)
740 #define RTC_DLOG_IF(sev, condition) RTC_LOG_IF(sev, condition)
741 #define RTC_DLOG_V(sev) RTC_LOG_V(sev)
742 #define RTC_DLOG_F(sev) RTC_LOG_F(sev)
743 #define RTC_DLOG_IF_F(sev, condition) RTC_LOG_IF_F(sev, condition)
744 #else
745 #define RTC_DLOG_EAT_STREAM_PARAMS() \
746 while (false) \
747 ::rtc::webrtc_logging_impl::LogMessageVoidify() & \
748 (::rtc::webrtc_logging_impl::LogStreamer<>())
749 #define RTC_DLOG(sev) RTC_DLOG_EAT_STREAM_PARAMS()
750 #define RTC_DLOG_IF(sev, condition) RTC_DLOG_EAT_STREAM_PARAMS()
751 #define RTC_DLOG_V(sev) RTC_DLOG_EAT_STREAM_PARAMS()
752 #define RTC_DLOG_F(sev) RTC_DLOG_EAT_STREAM_PARAMS()
753 #define RTC_DLOG_IF_F(sev, condition) RTC_DLOG_EAT_STREAM_PARAMS()
754 #endif
755
756 } // namespace rtc
757
758 #endif // RTC_BASE_LOGGING_H_
759