blob: 802dfa78d2b96ea7fae5d9845e8b6d5e09ebc9f8 [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
11// LOG(...) an ostream target that can be used to send formatted
12// output to a variety of logging targets, such as debugger console, stderr,
Tommi0eefb4d2015-05-23 09:54:07 +020013// or any LogSink.
henrike@webrtc.orgf0488722014-05-13 18:00:26 +000014// 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 LOG macro which facilitate logging
19// of common error conditions, detailed below.
20
21// 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// LOG_V(sev) Like LOG(), but sev is a run-time variable of the LoggingSeverity
25// type (basically, it just doesn't prepend the namespace).
26// LOG_F(sev) Like LOG(), but includes the name of the current function.
27// LOG_T(sev) Like LOG(), but includes the this pointer.
28// LOG_T_F(sev) Like LOG_F(), but includes the this pointer.
29// LOG_GLE(M)(sev [, mod]) attempt to add a string description of the
30// HRESULT returned by GetLastError. The "M" variant allows searching of a
31// DLL's string table for the error description.
32// LOG_ERRNO(sev) attempts to add a string description of an errno-derived
33// error. errno and associated facilities exist on both Windows and POSIX,
34// but on Windows they only apply to the C/C++ runtime.
35// LOG_ERR(sev) is an alias for the platform's normal error system, i.e. _GLE on
36// Windows and _ERRNO on POSIX.
37// (The above three also all have _EX versions that let you specify the error
38// code, rather than using the last one.)
39// LOG_E(sev, ctx, err, ...) logs a detailed error interpreted using the
40// specified context.
41// LOG_CHECK_LEVEL(sev) (and LOG_CHECK_LEVEL_V(sev)) can be used as a test
42// before performing expensive or sensitive operations whose sole purpose is
43// to output logging data at the desired level.
44// Lastly, PLOG(sev, err) is an alias for LOG_ERR_EX.
45
46#ifndef WEBRTC_BASE_LOGGING_H_
47#define WEBRTC_BASE_LOGGING_H_
48
henrike@webrtc.orgf0488722014-05-13 18:00:26 +000049#include <list>
50#include <sstream>
51#include <string>
52#include <utility>
Peter Boström225789d2015-10-23 15:20:56 +020053
Tommi09ca02e2016-04-24 17:32:48 +020054#if defined(WEBRTC_MAC) && !defined(WEBRTC_IOS)
55#include <CoreServices/CoreServices.h>
56#endif
57
henrike@webrtc.orgf0488722014-05-13 18:00:26 +000058#include "webrtc/base/basictypes.h"
Peter Boström225789d2015-10-23 15:20:56 +020059#include "webrtc/base/constructormagic.h"
Tommi00aac5a2015-05-25 11:25:59 +020060#include "webrtc/base/thread_annotations.h"
henrike@webrtc.orgf0488722014-05-13 18:00:26 +000061
62namespace rtc {
63
henrike@webrtc.orgf0488722014-05-13 18:00:26 +000064///////////////////////////////////////////////////////////////////////////////
65// ConstantLabel can be used to easily generate string names from constant
66// values. This can be useful for logging descriptive names of error messages.
67// Usage:
68// const ConstantLabel LIBRARY_ERRORS[] = {
69// KLABEL(SOME_ERROR),
70// KLABEL(SOME_OTHER_ERROR),
71// ...
72// LASTLABEL
73// }
74//
75// int err = LibraryFunc();
76// LOG(LS_ERROR) << "LibraryFunc returned: "
77// << ErrorName(err, LIBRARY_ERRORS);
78
79struct ConstantLabel { int value; const char * label; };
80#define KLABEL(x) { x, #x }
81#define TLABEL(x, y) { x, y }
82#define LASTLABEL { 0, 0 }
83
andrew88703d72015-09-07 00:34:56 -070084const char* FindLabel(int value, const ConstantLabel entries[]);
henrike@webrtc.orgf0488722014-05-13 18:00:26 +000085std::string ErrorName(int err, const ConstantLabel* err_table);
86
Tommi09ca02e2016-04-24 17:32:48 +020087#if defined(WEBRTC_MAC) && !defined(WEBRTC_IOS)
88// Returns a UTF8 description from an OS X Status error.
89std::string DescriptionFromOSStatus(OSStatus err);
90#endif
91
henrike@webrtc.orgf0488722014-05-13 18:00:26 +000092//////////////////////////////////////////////////////////////////////
93
94// Note that the non-standard LoggingSeverity aliases exist because they are
95// still in broad use. The meanings of the levels are:
96// LS_SENSITIVE: Information which should only be logged with the consent
97// of the user, due to privacy concerns.
98// LS_VERBOSE: This level is for data which we do not want to appear in the
99// normal debug log, but should appear in diagnostic logs.
100// LS_INFO: Chatty level used in debugging for all sorts of things, the default
101// in debug builds.
102// LS_WARNING: Something that may warrant investigation.
103// LS_ERROR: Something that should not have occurred.
Tommi0eefb4d2015-05-23 09:54:07 +0200104// LS_NONE: Don't log.
105enum LoggingSeverity {
106 LS_SENSITIVE,
107 LS_VERBOSE,
108 LS_INFO,
109 LS_WARNING,
110 LS_ERROR,
111 LS_NONE,
112 INFO = LS_INFO,
113 WARNING = LS_WARNING,
114 LERROR = LS_ERROR
115};
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000116
117// LogErrorContext assists in interpreting the meaning of an error value.
118enum LogErrorContext {
119 ERRCTX_NONE,
120 ERRCTX_ERRNO, // System-local errno
121 ERRCTX_HRESULT, // Windows HRESULT
122 ERRCTX_OSSTATUS, // MacOS OSStatus
123
124 // Abbreviations for LOG_E macro
125 ERRCTX_EN = ERRCTX_ERRNO, // LOG_E(sev, EN, x)
126 ERRCTX_HR = ERRCTX_HRESULT, // LOG_E(sev, HR, x)
127 ERRCTX_OS = ERRCTX_OSSTATUS, // LOG_E(sev, OS, x)
128};
129
Tommi0eefb4d2015-05-23 09:54:07 +0200130// Virtual sink interface that can receive log messages.
131class LogSink {
132 public:
133 LogSink() {}
134 virtual ~LogSink() {}
135 virtual void OnLogMessage(const std::string& message) = 0;
136};
137
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000138class LogMessage {
139 public:
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000140 LogMessage(const char* file, int line, LoggingSeverity sev,
141 LogErrorContext err_ctx = ERRCTX_NONE, int err = 0,
142 const char* module = NULL);
jiayl66f0da22015-09-14 15:06:39 -0700143
144 LogMessage(const char* file,
145 int line,
146 LoggingSeverity sev,
147 const std::string& tag);
148
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000149 ~LogMessage();
150
151 static inline bool Loggable(LoggingSeverity sev) { return (sev >= min_sev_); }
152 std::ostream& stream() { return print_stream_; }
153
154 // Returns the time at which this function was called for the first time.
155 // The time will be used as the logging start time.
156 // If this is not called externally, the LogMessage ctor also calls it, in
157 // which case the logging start time will be the time of the first LogMessage
158 // instance is created.
Honghai Zhang82d78622016-05-06 11:29:15 -0700159 static int64_t LogStartTime();
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000160
161 // Returns the wall clock equivalent of |LogStartTime|, in seconds from the
162 // epoch.
Peter Boström0c4e06b2015-10-07 12:23:21 +0200163 static uint32_t WallClockStartTime();
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000164
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000165 // LogThreads: Display the thread identifier of the current thread
166 static void LogThreads(bool on = true);
Tommi00aac5a2015-05-25 11:25:59 +0200167
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000168 // LogTimestamps: Display the elapsed time of the program
169 static void LogTimestamps(bool on = true);
170
171 // These are the available logging channels
172 // Debug: Debug console on Windows, otherwise stderr
Tommi0eefb4d2015-05-23 09:54:07 +0200173 static void LogToDebug(LoggingSeverity min_sev);
174 static LoggingSeverity GetLogToDebug() { return dbg_sev_; }
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000175
andrew88703d72015-09-07 00:34:56 -0700176 // Sets whether logs will be directed to stderr in debug mode.
177 static void SetLogToStderr(bool log_to_stderr);
178
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000179 // Stream: Any non-blocking stream interface. LogMessage takes ownership of
180 // the stream. Multiple streams may be specified by using AddLogToStream.
181 // LogToStream is retained for backwards compatibility; when invoked, it
182 // will discard any previously set streams and install the specified stream.
183 // GetLogToStream gets the severity for the specified stream, of if none
184 // is specified, the minimum stream severity.
185 // RemoveLogToStream removes the specified stream, without destroying it.
Tommi0eefb4d2015-05-23 09:54:07 +0200186 static int GetLogToStream(LogSink* stream = NULL);
187 static void AddLogToStream(LogSink* stream, LoggingSeverity min_sev);
188 static void RemoveLogToStream(LogSink* stream);
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000189
190 // Testing against MinLogSeverity allows code to avoid potentially expensive
191 // logging operations by pre-checking the logging level.
192 static int GetMinLogSeverity() { return min_sev_; }
193
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000194 // Parses the provided parameter stream to configure the options above.
Tommi0eefb4d2015-05-23 09:54:07 +0200195 // Useful for configuring logging from the command line.
196 static void ConfigureLogging(const char* params);
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000197
198 private:
Tommi0eefb4d2015-05-23 09:54:07 +0200199 typedef std::pair<LogSink*, LoggingSeverity> StreamAndSeverity;
200 typedef std::list<StreamAndSeverity> StreamList;
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000201
202 // Updates min_sev_ appropriately when debug sinks change.
Peter Boström225789d2015-10-23 15:20:56 +0200203 static void UpdateMinLogSeverity();
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000204
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000205 // These write out the actual log messages.
jiayl66f0da22015-09-14 15:06:39 -0700206 static void OutputToDebug(const std::string& msg,
207 LoggingSeverity severity,
208 const std::string& tag);
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000209
210 // The ostream that buffers the formatted message before output
211 std::ostringstream print_stream_;
212
213 // The severity level of this message
214 LoggingSeverity severity_;
215
jiayl66f0da22015-09-14 15:06:39 -0700216 // The Android debug output tag.
217 std::string tag_;
218
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000219 // String data generated in the constructor, that should be appended to
220 // the message before output.
221 std::string extra_;
222
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000223 // dbg_sev_ is the thresholds for those output targets
224 // min_sev_ is the minimum (most verbose) of those levels, and is used
225 // as a short-circuit in the logging macros to identify messages that won't
226 // be logged.
227 // ctx_sev_ is the minimum level at which file context is displayed
Tommi0eefb4d2015-05-23 09:54:07 +0200228 static LoggingSeverity min_sev_, dbg_sev_, ctx_sev_;
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000229
230 // The output streams and their associated severities
231 static StreamList streams_;
232
233 // Flags for formatting options
234 static bool thread_, timestamp_;
235
andrew88703d72015-09-07 00:34:56 -0700236 // Determines if logs will be directed to stderr in debug mode.
237 static bool log_to_stderr_;
238
henrikg3c089d72015-09-16 05:37:44 -0700239 RTC_DISALLOW_COPY_AND_ASSIGN(LogMessage);
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000240};
241
242//////////////////////////////////////////////////////////////////////
243// Logging Helpers
244//////////////////////////////////////////////////////////////////////
245
246class LogMultilineState {
247 public:
248 size_t unprintable_count_[2];
249 LogMultilineState() {
250 unprintable_count_[0] = unprintable_count_[1] = 0;
251 }
252};
253
254// When possible, pass optional state variable to track various data across
255// multiple calls to LogMultiline. Otherwise, pass NULL.
256void LogMultiline(LoggingSeverity level, const char* label, bool input,
257 const void* data, size_t len, bool hex_mode,
258 LogMultilineState* state);
259
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000260#ifndef LOG
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000261
262// The following non-obvious technique for implementation of a
263// conditional log stream was stolen from google3/base/logging.h.
264
265// This class is used to explicitly ignore values in the conditional
266// logging macros. This avoids compiler warnings like "value computed
267// is not used" and "statement has no effect".
268
269class LogMessageVoidify {
270 public:
271 LogMessageVoidify() { }
272 // This has to be an operator with a precedence lower than << but
273 // higher than ?:
274 void operator&(std::ostream&) { }
275};
276
277#define LOG_SEVERITY_PRECONDITION(sev) \
278 !(rtc::LogMessage::Loggable(sev)) \
279 ? (void) 0 \
280 : rtc::LogMessageVoidify() &
281
282#define LOG(sev) \
283 LOG_SEVERITY_PRECONDITION(rtc::sev) \
284 rtc::LogMessage(__FILE__, __LINE__, rtc::sev).stream()
285
286// The _V version is for when a variable is passed in. It doesn't do the
287// namespace concatination.
288#define LOG_V(sev) \
289 LOG_SEVERITY_PRECONDITION(sev) \
290 rtc::LogMessage(__FILE__, __LINE__, sev).stream()
291
292// The _F version prefixes the message with the current function name.
tfarinaa41ab932015-10-30 16:08:48 -0700293#if (defined(__GNUC__) && !defined(NDEBUG)) || defined(WANT_PRETTY_LOG_F)
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000294#define LOG_F(sev) LOG(sev) << __PRETTY_FUNCTION__ << ": "
295#define LOG_T_F(sev) LOG(sev) << this << ": " << __PRETTY_FUNCTION__ << ": "
296#else
297#define LOG_F(sev) LOG(sev) << __FUNCTION__ << ": "
298#define LOG_T_F(sev) LOG(sev) << this << ": " << __FUNCTION__ << ": "
299#endif
300
301#define LOG_CHECK_LEVEL(sev) \
302 rtc::LogCheckLevel(rtc::sev)
303#define LOG_CHECK_LEVEL_V(sev) \
304 rtc::LogCheckLevel(sev)
Tommi00aac5a2015-05-25 11:25:59 +0200305
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000306inline bool LogCheckLevel(LoggingSeverity sev) {
307 return (LogMessage::GetMinLogSeverity() <= sev);
308}
309
310#define LOG_E(sev, ctx, err, ...) \
311 LOG_SEVERITY_PRECONDITION(rtc::sev) \
312 rtc::LogMessage(__FILE__, __LINE__, rtc::sev, \
313 rtc::ERRCTX_ ## ctx, err , ##__VA_ARGS__) \
314 .stream()
315
316#define LOG_T(sev) LOG(sev) << this << ": "
317
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000318#define LOG_ERRNO_EX(sev, err) \
319 LOG_E(sev, ERRNO, err)
320#define LOG_ERRNO(sev) \
321 LOG_ERRNO_EX(sev, errno)
322
323#if defined(WEBRTC_WIN)
324#define LOG_GLE_EX(sev, err) \
325 LOG_E(sev, HRESULT, err)
326#define LOG_GLE(sev) \
327 LOG_GLE_EX(sev, GetLastError())
328#define LOG_GLEM(sev, mod) \
329 LOG_E(sev, HRESULT, GetLastError(), mod)
330#define LOG_ERR_EX(sev, err) \
331 LOG_GLE_EX(sev, err)
332#define LOG_ERR(sev) \
333 LOG_GLE(sev)
334#define LAST_SYSTEM_ERROR \
335 (::GetLastError())
336#elif __native_client__
337#define LOG_ERR_EX(sev, err) \
338 LOG(sev)
339#define LOG_ERR(sev) \
340 LOG(sev)
341#define LAST_SYSTEM_ERROR \
342 (0)
343#elif defined(WEBRTC_POSIX)
344#define LOG_ERR_EX(sev, err) \
345 LOG_ERRNO_EX(sev, err)
346#define LOG_ERR(sev) \
347 LOG_ERRNO(sev)
348#define LAST_SYSTEM_ERROR \
349 (errno)
Tommi0eefb4d2015-05-23 09:54:07 +0200350#endif // WEBRTC_WIN
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000351
jiayl66f0da22015-09-14 15:06:39 -0700352#define LOG_TAG(sev, tag) \
353 LOG_SEVERITY_PRECONDITION(sev) \
Alex Glaznevebed24d2015-09-15 11:05:24 -0700354 rtc::LogMessage(NULL, 0, sev, tag).stream()
jiayl66f0da22015-09-14 15:06:39 -0700355
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000356#define PLOG(sev, err) \
357 LOG_ERR_EX(sev, err)
358
359// TODO(?): Add an "assert" wrapper that logs in the same manner.
360
361#endif // LOG
362
363} // namespace rtc
364
365#endif // WEBRTC_BASE_LOGGING_H_