blob: 8c7b3f70e5284a5c0a7b76f69ab5e05ac089a7a8 [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
henrike@webrtc.orgf0488722014-05-13 18:00:26 +000054#include "webrtc/base/basictypes.h"
Peter Boström225789d2015-10-23 15:20:56 +020055#include "webrtc/base/constructormagic.h"
Tommi00aac5a2015-05-25 11:25:59 +020056#include "webrtc/base/thread_annotations.h"
henrike@webrtc.orgf0488722014-05-13 18:00:26 +000057
58namespace rtc {
59
henrike@webrtc.orgf0488722014-05-13 18:00:26 +000060///////////////////////////////////////////////////////////////////////////////
61// ConstantLabel can be used to easily generate string names from constant
62// values. This can be useful for logging descriptive names of error messages.
63// Usage:
64// const ConstantLabel LIBRARY_ERRORS[] = {
65// KLABEL(SOME_ERROR),
66// KLABEL(SOME_OTHER_ERROR),
67// ...
68// LASTLABEL
69// }
70//
71// int err = LibraryFunc();
72// LOG(LS_ERROR) << "LibraryFunc returned: "
73// << ErrorName(err, LIBRARY_ERRORS);
74
75struct ConstantLabel { int value; const char * label; };
76#define KLABEL(x) { x, #x }
77#define TLABEL(x, y) { x, y }
78#define LASTLABEL { 0, 0 }
79
andrew88703d72015-09-07 00:34:56 -070080const char* FindLabel(int value, const ConstantLabel entries[]);
henrike@webrtc.orgf0488722014-05-13 18:00:26 +000081std::string ErrorName(int err, const ConstantLabel* err_table);
82
83//////////////////////////////////////////////////////////////////////
84
85// Note that the non-standard LoggingSeverity aliases exist because they are
86// still in broad use. The meanings of the levels are:
87// LS_SENSITIVE: Information which should only be logged with the consent
88// of the user, due to privacy concerns.
89// LS_VERBOSE: This level is for data which we do not want to appear in the
90// normal debug log, but should appear in diagnostic logs.
91// LS_INFO: Chatty level used in debugging for all sorts of things, the default
92// in debug builds.
93// LS_WARNING: Something that may warrant investigation.
94// LS_ERROR: Something that should not have occurred.
Tommi0eefb4d2015-05-23 09:54:07 +020095// LS_NONE: Don't log.
96enum LoggingSeverity {
97 LS_SENSITIVE,
98 LS_VERBOSE,
99 LS_INFO,
100 LS_WARNING,
101 LS_ERROR,
102 LS_NONE,
103 INFO = LS_INFO,
104 WARNING = LS_WARNING,
105 LERROR = LS_ERROR
106};
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000107
108// LogErrorContext assists in interpreting the meaning of an error value.
109enum LogErrorContext {
110 ERRCTX_NONE,
111 ERRCTX_ERRNO, // System-local errno
112 ERRCTX_HRESULT, // Windows HRESULT
113 ERRCTX_OSSTATUS, // MacOS OSStatus
114
115 // Abbreviations for LOG_E macro
116 ERRCTX_EN = ERRCTX_ERRNO, // LOG_E(sev, EN, x)
117 ERRCTX_HR = ERRCTX_HRESULT, // LOG_E(sev, HR, x)
118 ERRCTX_OS = ERRCTX_OSSTATUS, // LOG_E(sev, OS, x)
119};
120
Tommi0eefb4d2015-05-23 09:54:07 +0200121// Virtual sink interface that can receive log messages.
122class LogSink {
123 public:
124 LogSink() {}
125 virtual ~LogSink() {}
126 virtual void OnLogMessage(const std::string& message) = 0;
127};
128
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000129class LogMessage {
130 public:
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000131 LogMessage(const char* file, int line, LoggingSeverity sev,
132 LogErrorContext err_ctx = ERRCTX_NONE, int err = 0,
133 const char* module = NULL);
jiayl66f0da22015-09-14 15:06:39 -0700134
135 LogMessage(const char* file,
136 int line,
137 LoggingSeverity sev,
138 const std::string& tag);
139
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000140 ~LogMessage();
141
142 static inline bool Loggable(LoggingSeverity sev) { return (sev >= min_sev_); }
143 std::ostream& stream() { return print_stream_; }
144
145 // Returns the time at which this function was called for the first time.
146 // The time will be used as the logging start time.
147 // If this is not called externally, the LogMessage ctor also calls it, in
148 // which case the logging start time will be the time of the first LogMessage
149 // instance is created.
Peter Boström0c4e06b2015-10-07 12:23:21 +0200150 static uint32_t LogStartTime();
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000151
152 // Returns the wall clock equivalent of |LogStartTime|, in seconds from the
153 // epoch.
Peter Boström0c4e06b2015-10-07 12:23:21 +0200154 static uint32_t WallClockStartTime();
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000155
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000156 // LogThreads: Display the thread identifier of the current thread
157 static void LogThreads(bool on = true);
Tommi00aac5a2015-05-25 11:25:59 +0200158
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000159 // LogTimestamps: Display the elapsed time of the program
160 static void LogTimestamps(bool on = true);
161
162 // These are the available logging channels
163 // Debug: Debug console on Windows, otherwise stderr
Tommi0eefb4d2015-05-23 09:54:07 +0200164 static void LogToDebug(LoggingSeverity min_sev);
165 static LoggingSeverity GetLogToDebug() { return dbg_sev_; }
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000166
andrew88703d72015-09-07 00:34:56 -0700167 // Sets whether logs will be directed to stderr in debug mode.
168 static void SetLogToStderr(bool log_to_stderr);
169
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000170 // Stream: Any non-blocking stream interface. LogMessage takes ownership of
171 // the stream. Multiple streams may be specified by using AddLogToStream.
172 // LogToStream is retained for backwards compatibility; when invoked, it
173 // will discard any previously set streams and install the specified stream.
174 // GetLogToStream gets the severity for the specified stream, of if none
175 // is specified, the minimum stream severity.
176 // RemoveLogToStream removes the specified stream, without destroying it.
Tommi0eefb4d2015-05-23 09:54:07 +0200177 static int GetLogToStream(LogSink* stream = NULL);
178 static void AddLogToStream(LogSink* stream, LoggingSeverity min_sev);
179 static void RemoveLogToStream(LogSink* stream);
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000180
181 // Testing against MinLogSeverity allows code to avoid potentially expensive
182 // logging operations by pre-checking the logging level.
183 static int GetMinLogSeverity() { return min_sev_; }
184
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000185 // Parses the provided parameter stream to configure the options above.
Tommi0eefb4d2015-05-23 09:54:07 +0200186 // Useful for configuring logging from the command line.
187 static void ConfigureLogging(const char* params);
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000188
189 private:
Tommi0eefb4d2015-05-23 09:54:07 +0200190 typedef std::pair<LogSink*, LoggingSeverity> StreamAndSeverity;
191 typedef std::list<StreamAndSeverity> StreamList;
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000192
193 // Updates min_sev_ appropriately when debug sinks change.
Peter Boström225789d2015-10-23 15:20:56 +0200194 static void UpdateMinLogSeverity();
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000195
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000196 // These write out the actual log messages.
jiayl66f0da22015-09-14 15:06:39 -0700197 static void OutputToDebug(const std::string& msg,
198 LoggingSeverity severity,
199 const std::string& tag);
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000200
201 // The ostream that buffers the formatted message before output
202 std::ostringstream print_stream_;
203
204 // The severity level of this message
205 LoggingSeverity severity_;
206
jiayl66f0da22015-09-14 15:06:39 -0700207 // The Android debug output tag.
208 std::string tag_;
209
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000210 // String data generated in the constructor, that should be appended to
211 // the message before output.
212 std::string extra_;
213
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000214 // dbg_sev_ is the thresholds for those output targets
215 // min_sev_ is the minimum (most verbose) of those levels, and is used
216 // as a short-circuit in the logging macros to identify messages that won't
217 // be logged.
218 // ctx_sev_ is the minimum level at which file context is displayed
Tommi0eefb4d2015-05-23 09:54:07 +0200219 static LoggingSeverity min_sev_, dbg_sev_, ctx_sev_;
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000220
221 // The output streams and their associated severities
222 static StreamList streams_;
223
224 // Flags for formatting options
225 static bool thread_, timestamp_;
226
andrew88703d72015-09-07 00:34:56 -0700227 // Determines if logs will be directed to stderr in debug mode.
228 static bool log_to_stderr_;
229
henrikg3c089d72015-09-16 05:37:44 -0700230 RTC_DISALLOW_COPY_AND_ASSIGN(LogMessage);
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000231};
232
233//////////////////////////////////////////////////////////////////////
234// Logging Helpers
235//////////////////////////////////////////////////////////////////////
236
237class LogMultilineState {
238 public:
239 size_t unprintable_count_[2];
240 LogMultilineState() {
241 unprintable_count_[0] = unprintable_count_[1] = 0;
242 }
243};
244
245// When possible, pass optional state variable to track various data across
246// multiple calls to LogMultiline. Otherwise, pass NULL.
247void LogMultiline(LoggingSeverity level, const char* label, bool input,
248 const void* data, size_t len, bool hex_mode,
249 LogMultilineState* state);
250
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000251#ifndef LOG
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000252
253// The following non-obvious technique for implementation of a
254// conditional log stream was stolen from google3/base/logging.h.
255
256// This class is used to explicitly ignore values in the conditional
257// logging macros. This avoids compiler warnings like "value computed
258// is not used" and "statement has no effect".
259
260class LogMessageVoidify {
261 public:
262 LogMessageVoidify() { }
263 // This has to be an operator with a precedence lower than << but
264 // higher than ?:
265 void operator&(std::ostream&) { }
266};
267
268#define LOG_SEVERITY_PRECONDITION(sev) \
269 !(rtc::LogMessage::Loggable(sev)) \
270 ? (void) 0 \
271 : rtc::LogMessageVoidify() &
272
273#define LOG(sev) \
274 LOG_SEVERITY_PRECONDITION(rtc::sev) \
275 rtc::LogMessage(__FILE__, __LINE__, rtc::sev).stream()
276
277// The _V version is for when a variable is passed in. It doesn't do the
278// namespace concatination.
279#define LOG_V(sev) \
280 LOG_SEVERITY_PRECONDITION(sev) \
281 rtc::LogMessage(__FILE__, __LINE__, sev).stream()
282
283// The _F version prefixes the message with the current function name.
tfarinaa41ab932015-10-30 16:08:48 -0700284#if (defined(__GNUC__) && !defined(NDEBUG)) || defined(WANT_PRETTY_LOG_F)
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000285#define LOG_F(sev) LOG(sev) << __PRETTY_FUNCTION__ << ": "
286#define LOG_T_F(sev) LOG(sev) << this << ": " << __PRETTY_FUNCTION__ << ": "
287#else
288#define LOG_F(sev) LOG(sev) << __FUNCTION__ << ": "
289#define LOG_T_F(sev) LOG(sev) << this << ": " << __FUNCTION__ << ": "
290#endif
291
292#define LOG_CHECK_LEVEL(sev) \
293 rtc::LogCheckLevel(rtc::sev)
294#define LOG_CHECK_LEVEL_V(sev) \
295 rtc::LogCheckLevel(sev)
Tommi00aac5a2015-05-25 11:25:59 +0200296
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000297inline bool LogCheckLevel(LoggingSeverity sev) {
298 return (LogMessage::GetMinLogSeverity() <= sev);
299}
300
301#define LOG_E(sev, ctx, err, ...) \
302 LOG_SEVERITY_PRECONDITION(rtc::sev) \
303 rtc::LogMessage(__FILE__, __LINE__, rtc::sev, \
304 rtc::ERRCTX_ ## ctx, err , ##__VA_ARGS__) \
305 .stream()
306
307#define LOG_T(sev) LOG(sev) << this << ": "
308
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000309#define LOG_ERRNO_EX(sev, err) \
310 LOG_E(sev, ERRNO, err)
311#define LOG_ERRNO(sev) \
312 LOG_ERRNO_EX(sev, errno)
313
314#if defined(WEBRTC_WIN)
315#define LOG_GLE_EX(sev, err) \
316 LOG_E(sev, HRESULT, err)
317#define LOG_GLE(sev) \
318 LOG_GLE_EX(sev, GetLastError())
319#define LOG_GLEM(sev, mod) \
320 LOG_E(sev, HRESULT, GetLastError(), mod)
321#define LOG_ERR_EX(sev, err) \
322 LOG_GLE_EX(sev, err)
323#define LOG_ERR(sev) \
324 LOG_GLE(sev)
325#define LAST_SYSTEM_ERROR \
326 (::GetLastError())
327#elif __native_client__
328#define LOG_ERR_EX(sev, err) \
329 LOG(sev)
330#define LOG_ERR(sev) \
331 LOG(sev)
332#define LAST_SYSTEM_ERROR \
333 (0)
334#elif defined(WEBRTC_POSIX)
335#define LOG_ERR_EX(sev, err) \
336 LOG_ERRNO_EX(sev, err)
337#define LOG_ERR(sev) \
338 LOG_ERRNO(sev)
339#define LAST_SYSTEM_ERROR \
340 (errno)
Tommi0eefb4d2015-05-23 09:54:07 +0200341#endif // WEBRTC_WIN
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000342
jiayl66f0da22015-09-14 15:06:39 -0700343#define LOG_TAG(sev, tag) \
344 LOG_SEVERITY_PRECONDITION(sev) \
Alex Glaznevebed24d2015-09-15 11:05:24 -0700345 rtc::LogMessage(NULL, 0, sev, tag).stream()
jiayl66f0da22015-09-14 15:06:39 -0700346
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000347#define PLOG(sev, err) \
348 LOG_ERR_EX(sev, err)
349
350// TODO(?): Add an "assert" wrapper that logs in the same manner.
351
352#endif // LOG
353
354} // namespace rtc
355
356#endif // WEBRTC_BASE_LOGGING_H_