/* * Copyright 2004 The WebRTC Project Authors. All rights reserved. * * Use of this source code is governed by a BSD-style license * that can be found in the LICENSE file in the root of the source * tree. An additional intellectual property rights grant can be found * in the file PATENTS. All contributing project authors may * be found in the AUTHORS file in the root of the source tree.
*/
// RTC_LOG(...) an ostream target that can be used to send formatted // output to a variety of logging targets, such as debugger console, stderr, // or any LogSink. // The severity level passed as the first argument to the logging // functions is used as a filter, to limit the verbosity of the logging. // Static members of LogMessage documented below are used to control the // verbosity and target of the output. // There are several variations on the RTC_LOG macro which facilitate logging // of common error conditions, detailed below.
// RTC_LOG(sev) logs the given stream at severity "sev", which must be a // compile-time constant of the LoggingSeverity type, without the namespace // prefix. // RTC_LOG_IF(sev, condition) logs the given stream at severity "sev" if // "condition" is true. // RTC_LOG_V(sev) Like RTC_LOG(), but sev is a run-time variable of the // LoggingSeverity type (basically, it just doesn't prepend the namespace). // RTC_LOG_F(sev) Like RTC_LOG(), but includes the name of the current function. // RTC_LOG_IF_F(sev, condition), Like RTC_LOG_IF(), but includes the name of // the current function. // RTC_LOG_T(sev) Like RTC_LOG(), but includes the this pointer. // RTC_LOG_T_F(sev) Like RTC_LOG_F(), but includes the this pointer. // RTC_LOG_GLE(sev [, mod]) attempt to add a string description of the // HRESULT returned by GetLastError. // RTC_LOG_ERRNO(sev) attempts to add a string description of an errno-derived // error. errno and associated facilities exist on both Windows and POSIX, // but on Windows they only apply to the C/C++ runtime. // RTC_LOG_ERR(sev) is an alias for the platform's normal error system, i.e. // _GLE on Windows and _ERRNO on POSIX. // (The above three also all have _EX versions that let you specify the error // code, rather than using the last one.) // RTC_LOG_E(sev, ctx, err, ...) logs a detailed error interpreted using the // specified context. // RTC_LOG_CHECK_LEVEL(sev) (and RTC_LOG_CHECK_LEVEL_V(sev)) can be used as a // test before performing expensive or sensitive operations whose sole // purpose is to output logging data at the desired level.
////////////////////////////////////////////////////////////////////// // The meanings of the levels are: // LS_VERBOSE: This level is for data which we do not want to appear in the // normal debug log, but should appear in diagnostic logs. // LS_INFO: Chatty level used in debugging for all sorts of things, the default // in debug builds. // LS_WARNING: Something that may warrant investigation. // LS_ERROR: Something that should not have occurred. // LS_NONE: Don't log. enum LoggingSeverity {
LS_VERBOSE,
LS_INFO,
LS_WARNING,
LS_ERROR,
LS_NONE,
};
// LogErrorContext assists in interpreting the meaning of an error value. enum LogErrorContext {
ERRCTX_NONE,
ERRCTX_ERRNO, // System-local errno
ERRCTX_HRESULT, // Windows HRESULT
// LogLineRef encapsulates all the information required to generate a log line. // It is used both internally to LogMessage but also as a parameter to // LogSink::OnLogMessage, allowing custom LogSinks to format the log in // the most flexible way. class LogLineRef { public:
absl::string_view message() const { return message_; }
absl::string_view filename() const { return filename_; } int line() const { return line_; }
std::optional<PlatformThreadId> thread_id() const { return thread_id_; }
webrtc::Timestamp timestamp() const { return timestamp_; }
absl::string_view tag() const { return tag_; }
LoggingSeverity severity() const { return severity_; }
private: friendclass ::rtc::LogMessage; #if RTC_LOG_ENABLED() // Members for LogMessage class to keep linked list of the registered sinks.
LogSink* next_ = nullptr;
LoggingSeverity min_severity_; #endif
};
// Line number and severity, the former in the most significant 29 bits, the // latter in the least significant 3 bits. (This is an optimization; since // both numbers are usually compile-time constants, this way we can load them // both with a single instruction.)
uint32_t line_and_sev_;
};
static_assert(std::is_trivial<LogMetadata>::value, "");
struct LogMetadataErr {
LogMetadata meta;
LogErrorContext err_ctx; int err;
};
// Wrapper for log arguments. Only ever make values of this type with the // MakeVal() functions. template <LogArgType N, typename T> struct Val { static constexpr LogArgType Type() { return N; }
T GetVal() const { return val; }
T val;
};
// Case for when we need to construct a temp string and then print that. // (We can't use Val<CheckArgType::kStdString, const std::string*> // because we need somewhere to store the temp string.) struct ToStringVal { static constexpr LogArgType Type() { return LogArgType::kStdString; } const std::string* GetVal() const { return &val; }
std::string val;
};
// The enum class types are not implicitly convertible to arithmetic types. template <typename T,
absl::enable_if_t<std::is_enum<T>::value &&
!std::is_arithmetic<T>::value>* = nullptr> inline decltype(MakeVal(std::declval<absl::underlying_type_t<T>>())) MakeVal(
T x) { return {static_cast<absl::underlying_type_t<T>>(x)};
}
// Handle arbitrary types other than the above by falling back to stringstream. // TODO(bugs.webrtc.org/9278): Get rid of this overload when callers don't need // it anymore. No in-tree caller does, but some external callers still do. template <typename T, typename T1 = absl::decay_t<T>,
std::enable_if_t<std::is_class<T1>::value && //
!std::is_same<T1, std::string>::value && //
!std::is_same<T1, LogMetadata>::value && //
!absl::HasAbslStringify<T1>::value && #ifdef WEBRTC_ANDROID
!std::is_same<T1, LogMetadataTag>::value && // #endif
!std::is_same<T1, LogMetadataErr>::value>* = nullptr>
ToStringVal MakeVal(const T& x) {
std::ostringstream os; // no-presubmit-check TODO(webrtc:8982)
os << x; return {os.str()};
}
// Ephemeral type that represents the result of the logging << operator. template <typename... Ts> class LogStreamer;
// Base case: Before the first << argument. template <> class LogStreamer<> final { public: template <typename U, typename V = decltype(MakeVal(std::declval<U>()))>
RTC_FORCE_INLINE LogStreamer<V> operator<<(const U& arg) const { return LogStreamer<V>(MakeVal(arg), this);
}
// Inductive case: We've already seen at least one << argument. The most recent // one had type `T`, and the earlier ones had types `Ts`. template <typename T, typename... Ts> class LogStreamer<T, Ts...> final { public:
RTC_FORCE_INLINE LogStreamer(T arg, const LogStreamer<Ts...>* prior)
: arg_(arg), prior_(prior) {}
class LogCall final { public: // This can be any binary operator with precedence lower than <<. // We return bool here to be able properly remove logging if // RTC_DISABLE_LOGGING is defined. template <typename... Ts>
RTC_FORCE_INLINE booloperator&(const LogStreamer<Ts...>& streamer) {
streamer.Call(); returntrue;
}
};
// This class is used to explicitly ignore values in the conditional // logging macros. This avoids compiler warnings like "value computed // is not used" and "statement has no effect". class LogMessageVoidify { public:
LogMessageVoidify() = default; // This has to be an operator with a precedence lower than << but // higher than ?: template <typename... Ts> voidoperator&(LogStreamer<Ts...>&& /* streamer */) {}
};
} // namespace webrtc_logging_impl
// Direct use of this class is deprecated; please use the logging macros // instead. // TODO(bugs.webrtc.org/9278): Move this class to an unnamed namespace in the // .cc file. class LogMessage { public: // Same as the above, but using a compile-time constant for the logging // severity. This saves space at the call site, since passing an empty struct // is generally the same as not passing an argument at all. template <LoggingSeverity S>
RTC_NO_INLINE LogMessage(constchar* file, int line,
std::integral_constant<LoggingSeverity, S>)
: LogMessage(file, line, S) {}
#if RTC_LOG_ENABLED()
LogMessage(constchar* file, int line, LoggingSeverity sev);
LogMessage(constchar* file, int line,
LoggingSeverity sev,
LogErrorContext err_ctx, int err); #ifdefined(WEBRTC_ANDROID)
LogMessage(constchar* file, int line, LoggingSeverity sev, constchar* tag); #endif
~LogMessage();
void AddTag(constchar* tag);
rtc::StringBuilder& stream(); // Returns the time at which this function was called for the first time. // The time will be used as the logging start time. // If this is not called externally, the LogMessage ctor also calls it, in // which case the logging start time will be the time of the first LogMessage // instance is created. static int64_t LogStartTime(); // Returns the wall clock equivalent of `LogStartTime`, in seconds from the // epoch. static uint32_t WallClockStartTime(); // LogThreads: Display the thread identifier of the current thread staticvoid LogThreads(bool on = true); // LogTimestamps: Display the elapsed time of the program staticvoid LogTimestamps(bool on = true); // These are the available logging channels // Debug: Debug console on Windows, otherwise stderr staticvoid LogToDebug(LoggingSeverity min_sev); static LoggingSeverity GetLogToDebug(); // Sets whether logs will be directed to stderr in debug mode. staticvoid SetLogToStderr(bool log_to_stderr); // Stream: Any non-blocking stream interface. // Installs the `stream` to collect logs with severtiy `min_sev` or higher. // `stream` must live until deinstalled by RemoveLogToStream. // If `stream` is the first stream added to the system, we might miss some // early concurrent log statement happening from another thread happening near // this instant. staticvoid AddLogToStream(LogSink* stream, LoggingSeverity min_sev); // Removes the specified stream, without destroying it. When the method // has completed, it's guaranteed that `stream` will receive no more logging // calls. staticvoid RemoveLogToStream(LogSink* stream); // Returns the severity for the specified stream, of if none is specified, // the minimum stream severity. staticint GetLogToStream(LogSink* stream = nullptr); // Testing against MinLogSeverity allows code to avoid potentially expensive // logging operations by pre-checking the logging level. staticint GetMinLogSeverity(); // Parses the provided parameter stream to configure the options above. // Useful for configuring logging from the command line. staticvoid ConfigureLogging(absl::string_view params); // Checks the current global debug severity and if the `streams_` collection // is empty. If `severity` is smaller than the global severity and if the // `streams_` collection is empty, the LogMessage will be considered a noop // LogMessage. staticbool IsNoop(LoggingSeverity severity); // Version of IsNoop that uses fewer instructions at the call site, since the // caller doesn't have to pass an argument. template <LoggingSeverity S>
RTC_NO_INLINE staticbool IsNoop() { return IsNoop(S);
} #else // Next methods do nothing; no one will call these functions.
LogMessage(constchar* file, int line, LoggingSeverity sev) {}
LogMessage(constchar* file, int line,
LoggingSeverity sev,
LogErrorContext err_ctx, int err) {} #ifdefined(WEBRTC_ANDROID)
LogMessage(constchar* file, int line, LoggingSeverity sev, constchar* tag) {
} #endif
~LogMessage() = default;
// This writes out the actual log messages. staticvoid OutputToDebug(const LogLineRef& log_line_ref);
// Called from the dtor (or from a test) to append optional extra error // information to the log stream and a newline character. void FinishPrintStream();
LogLineRef log_line_;
// String data generated in the constructor, that should be appended to // the message before output.
std::string extra_;
// The output streams and their associated severities static LogSink* streams_;
// Holds true with high probability if `streams_` is empty, false with high // probability otherwise. Operated on with std::memory_order_relaxed because // it's ok to lose or log some additional statements near the instant streams // are added/removed. static std::atomic<bool> streams_empty_;
// Flags for formatting options and their potential values. staticbool log_thread_; staticbool log_timestamp_;
// Determines if logs will be directed to stderr in debug mode. staticbool log_to_stderr_; #else// RTC_LOG_ENABLED() // Next methods do nothing; no one will call these functions. inlinestaticvoid UpdateMinLogSeverity() {} #ifdefined(WEBRTC_ANDROID) inlinestaticvoid OutputToDebug(absl::string_view filename, int line,
absl::string_view msg,
LoggingSeverity severity, constchar* tag) {} #else inlinestaticvoid OutputToDebug(absl::string_view filename, int line,
absl::string_view msg,
LoggingSeverity severity) {} #endif// defined(WEBRTC_ANDROID) inlinevoid FinishPrintStream() {} #endif// RTC_LOG_ENABLED()
// The stringbuilder that buffers the formatted message before output
rtc::StringBuilder print_stream_;
// The _V version is for when a variable is passed in. #define RTC_LOG_V(sev) \
!::rtc::LogMessage::IsNoop(sev) && RTC_LOG_FILE_LINE(sev, __FILE__, __LINE__)
// The _F version prefixes the message with the current function name. #if (defined(__GNUC__) && !defined(NDEBUG)) || defined(WANT_PRETTY_LOG_F) #define RTC_LOG_F(sev) RTC_LOG(sev) << __PRETTY_FUNCTION__ << ": " #define RTC_LOG_IF_F(sev, condition) \
RTC_LOG_IF(sev, condition) << __PRETTY_FUNCTION__ << ": " #define RTC_LOG_T_F(sev) \
RTC_LOG(sev) << this << ": " << __PRETTY_FUNCTION__ << ": " #else #define RTC_LOG_F(sev) RTC_LOG(sev) << __FUNCTION__ << ": " #define RTC_LOG_IF_F(sev, condition) \
RTC_LOG_IF(sev, condition) << __FUNCTION__ << ": " #define RTC_LOG_T_F(sev) RTC_LOG(sev) << this << ": " << __FUNCTION__ << ": " #endif
Die Informationen auf dieser Webseite wurden
nach bestem Wissen sorgfältig zusammengestellt. Es wird jedoch weder Vollständigkeit, noch Richtigkeit,
noch Qualität der bereit gestellten Informationen zugesichert.
Bemerkung:
Die farbliche Syntaxdarstellung und die Messung sind noch experimentell.