blob: 71c6c53482e1278605535ab18955c107a2fcbfd6 [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
49#ifdef HAVE_CONFIG_H
50#include "config.h" // NOLINT
51#endif
52
53#include <list>
54#include <sstream>
55#include <string>
56#include <utility>
57#include "webrtc/base/basictypes.h"
58#include "webrtc/base/criticalsection.h"
Tommi00aac5a2015-05-25 11:25:59 +020059#include "webrtc/base/thread_annotations.h"
henrike@webrtc.orgf0488722014-05-13 18:00:26 +000060
61namespace rtc {
62
henrike@webrtc.orgf0488722014-05-13 18:00:26 +000063///////////////////////////////////////////////////////////////////////////////
64// ConstantLabel can be used to easily generate string names from constant
65// values. This can be useful for logging descriptive names of error messages.
66// Usage:
67// const ConstantLabel LIBRARY_ERRORS[] = {
68// KLABEL(SOME_ERROR),
69// KLABEL(SOME_OTHER_ERROR),
70// ...
71// LASTLABEL
72// }
73//
74// int err = LibraryFunc();
75// LOG(LS_ERROR) << "LibraryFunc returned: "
76// << ErrorName(err, LIBRARY_ERRORS);
77
78struct ConstantLabel { int value; const char * label; };
79#define KLABEL(x) { x, #x }
80#define TLABEL(x, y) { x, y }
81#define LASTLABEL { 0, 0 }
82
andrew88703d72015-09-07 00:34:56 -070083const char* FindLabel(int value, const ConstantLabel entries[]);
henrike@webrtc.orgf0488722014-05-13 18:00:26 +000084std::string ErrorName(int err, const ConstantLabel* err_table);
85
86//////////////////////////////////////////////////////////////////////
87
88// Note that the non-standard LoggingSeverity aliases exist because they are
89// still in broad use. The meanings of the levels are:
90// LS_SENSITIVE: Information which should only be logged with the consent
91// of the user, due to privacy concerns.
92// LS_VERBOSE: This level is for data which we do not want to appear in the
93// normal debug log, but should appear in diagnostic logs.
94// LS_INFO: Chatty level used in debugging for all sorts of things, the default
95// in debug builds.
96// LS_WARNING: Something that may warrant investigation.
97// LS_ERROR: Something that should not have occurred.
Tommi0eefb4d2015-05-23 09:54:07 +020098// LS_NONE: Don't log.
99enum LoggingSeverity {
100 LS_SENSITIVE,
101 LS_VERBOSE,
102 LS_INFO,
103 LS_WARNING,
104 LS_ERROR,
105 LS_NONE,
106 INFO = LS_INFO,
107 WARNING = LS_WARNING,
108 LERROR = LS_ERROR
109};
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000110
111// LogErrorContext assists in interpreting the meaning of an error value.
112enum LogErrorContext {
113 ERRCTX_NONE,
114 ERRCTX_ERRNO, // System-local errno
115 ERRCTX_HRESULT, // Windows HRESULT
116 ERRCTX_OSSTATUS, // MacOS OSStatus
117
118 // Abbreviations for LOG_E macro
119 ERRCTX_EN = ERRCTX_ERRNO, // LOG_E(sev, EN, x)
120 ERRCTX_HR = ERRCTX_HRESULT, // LOG_E(sev, HR, x)
121 ERRCTX_OS = ERRCTX_OSSTATUS, // LOG_E(sev, OS, x)
122};
123
Tommi0eefb4d2015-05-23 09:54:07 +0200124// Virtual sink interface that can receive log messages.
125class LogSink {
126 public:
127 LogSink() {}
128 virtual ~LogSink() {}
129 virtual void OnLogMessage(const std::string& message) = 0;
130};
131
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000132class LogMessage {
133 public:
Peter Boström0c4e06b2015-10-07 12:23:21 +0200134 static const uint32_t WARN_SLOW_LOGS_DELAY = 50; // ms
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000135
136 LogMessage(const char* file, int line, LoggingSeverity sev,
137 LogErrorContext err_ctx = ERRCTX_NONE, int err = 0,
138 const char* module = NULL);
jiayl66f0da22015-09-14 15:06:39 -0700139
140 LogMessage(const char* file,
141 int line,
142 LoggingSeverity sev,
143 const std::string& tag);
144
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000145 ~LogMessage();
146
147 static inline bool Loggable(LoggingSeverity sev) { return (sev >= min_sev_); }
148 std::ostream& stream() { return print_stream_; }
149
150 // Returns the time at which this function was called for the first time.
151 // The time will be used as the logging start time.
152 // If this is not called externally, the LogMessage ctor also calls it, in
153 // which case the logging start time will be the time of the first LogMessage
154 // instance is created.
Peter Boström0c4e06b2015-10-07 12:23:21 +0200155 static uint32_t LogStartTime();
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000156
157 // Returns the wall clock equivalent of |LogStartTime|, in seconds from the
158 // epoch.
Peter Boström0c4e06b2015-10-07 12:23:21 +0200159 static uint32_t WallClockStartTime();
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000160
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000161 // LogThreads: Display the thread identifier of the current thread
162 static void LogThreads(bool on = true);
Tommi00aac5a2015-05-25 11:25:59 +0200163
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000164 // LogTimestamps: Display the elapsed time of the program
165 static void LogTimestamps(bool on = true);
166
167 // These are the available logging channels
168 // Debug: Debug console on Windows, otherwise stderr
Tommi0eefb4d2015-05-23 09:54:07 +0200169 static void LogToDebug(LoggingSeverity min_sev);
170 static LoggingSeverity GetLogToDebug() { return dbg_sev_; }
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000171
andrew88703d72015-09-07 00:34:56 -0700172 // Sets whether logs will be directed to stderr in debug mode.
173 static void SetLogToStderr(bool log_to_stderr);
174
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000175 // Stream: Any non-blocking stream interface. LogMessage takes ownership of
176 // the stream. Multiple streams may be specified by using AddLogToStream.
177 // LogToStream is retained for backwards compatibility; when invoked, it
178 // will discard any previously set streams and install the specified stream.
179 // GetLogToStream gets the severity for the specified stream, of if none
180 // is specified, the minimum stream severity.
181 // RemoveLogToStream removes the specified stream, without destroying it.
Tommi0eefb4d2015-05-23 09:54:07 +0200182 static int GetLogToStream(LogSink* stream = NULL);
183 static void AddLogToStream(LogSink* stream, LoggingSeverity min_sev);
184 static void RemoveLogToStream(LogSink* stream);
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000185
186 // Testing against MinLogSeverity allows code to avoid potentially expensive
187 // logging operations by pre-checking the logging level.
188 static int GetMinLogSeverity() { return min_sev_; }
189
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000190 // Parses the provided parameter stream to configure the options above.
Tommi0eefb4d2015-05-23 09:54:07 +0200191 // Useful for configuring logging from the command line.
192 static void ConfigureLogging(const char* params);
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000193
194 private:
Tommi0eefb4d2015-05-23 09:54:07 +0200195 typedef std::pair<LogSink*, LoggingSeverity> StreamAndSeverity;
196 typedef std::list<StreamAndSeverity> StreamList;
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000197
198 // Updates min_sev_ appropriately when debug sinks change.
Tommi00aac5a2015-05-25 11:25:59 +0200199 static void UpdateMinLogSeverity() EXCLUSIVE_LOCKS_REQUIRED(crit_);
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000200
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000201 // These write out the actual log messages.
jiayl66f0da22015-09-14 15:06:39 -0700202 static void OutputToDebug(const std::string& msg,
203 LoggingSeverity severity,
204 const std::string& tag);
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000205
206 // The ostream that buffers the formatted message before output
207 std::ostringstream print_stream_;
208
209 // The severity level of this message
210 LoggingSeverity severity_;
211
jiayl66f0da22015-09-14 15:06:39 -0700212 // The Android debug output tag.
213 std::string tag_;
214
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000215 // String data generated in the constructor, that should be appended to
216 // the message before output.
217 std::string extra_;
218
219 // If time it takes to write to stream is more than this, log one
220 // additional warning about it.
Peter Boström0c4e06b2015-10-07 12:23:21 +0200221 uint32_t warn_slow_logs_delay_;
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000222
223 // Global lock for the logging subsystem
224 static CriticalSection crit_;
225
226 // dbg_sev_ is the thresholds for those output targets
227 // min_sev_ is the minimum (most verbose) of those levels, and is used
228 // as a short-circuit in the logging macros to identify messages that won't
229 // be logged.
230 // ctx_sev_ is the minimum level at which file context is displayed
Tommi0eefb4d2015-05-23 09:54:07 +0200231 static LoggingSeverity min_sev_, dbg_sev_, ctx_sev_;
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000232
233 // The output streams and their associated severities
234 static StreamList streams_;
235
236 // Flags for formatting options
237 static bool thread_, timestamp_;
238
andrew88703d72015-09-07 00:34:56 -0700239 // Determines if logs will be directed to stderr in debug mode.
240 static bool log_to_stderr_;
241
henrikg3c089d72015-09-16 05:37:44 -0700242 RTC_DISALLOW_COPY_AND_ASSIGN(LogMessage);
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000243};
244
245//////////////////////////////////////////////////////////////////////
246// Logging Helpers
247//////////////////////////////////////////////////////////////////////
248
249class LogMultilineState {
250 public:
251 size_t unprintable_count_[2];
252 LogMultilineState() {
253 unprintable_count_[0] = unprintable_count_[1] = 0;
254 }
255};
256
257// When possible, pass optional state variable to track various data across
258// multiple calls to LogMultiline. Otherwise, pass NULL.
259void LogMultiline(LoggingSeverity level, const char* label, bool input,
260 const void* data, size_t len, bool hex_mode,
261 LogMultilineState* state);
262
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000263#ifndef LOG
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000264
265// The following non-obvious technique for implementation of a
266// conditional log stream was stolen from google3/base/logging.h.
267
268// This class is used to explicitly ignore values in the conditional
269// logging macros. This avoids compiler warnings like "value computed
270// is not used" and "statement has no effect".
271
272class LogMessageVoidify {
273 public:
274 LogMessageVoidify() { }
275 // This has to be an operator with a precedence lower than << but
276 // higher than ?:
277 void operator&(std::ostream&) { }
278};
279
280#define LOG_SEVERITY_PRECONDITION(sev) \
281 !(rtc::LogMessage::Loggable(sev)) \
282 ? (void) 0 \
283 : rtc::LogMessageVoidify() &
284
285#define LOG(sev) \
286 LOG_SEVERITY_PRECONDITION(rtc::sev) \
287 rtc::LogMessage(__FILE__, __LINE__, rtc::sev).stream()
288
289// The _V version is for when a variable is passed in. It doesn't do the
290// namespace concatination.
291#define LOG_V(sev) \
292 LOG_SEVERITY_PRECONDITION(sev) \
293 rtc::LogMessage(__FILE__, __LINE__, sev).stream()
294
295// The _F version prefixes the message with the current function name.
296#if (defined(__GNUC__) && defined(_DEBUG)) || defined(WANT_PRETTY_LOG_F)
297#define LOG_F(sev) LOG(sev) << __PRETTY_FUNCTION__ << ": "
298#define LOG_T_F(sev) LOG(sev) << this << ": " << __PRETTY_FUNCTION__ << ": "
299#else
300#define LOG_F(sev) LOG(sev) << __FUNCTION__ << ": "
301#define LOG_T_F(sev) LOG(sev) << this << ": " << __FUNCTION__ << ": "
302#endif
303
304#define LOG_CHECK_LEVEL(sev) \
305 rtc::LogCheckLevel(rtc::sev)
306#define LOG_CHECK_LEVEL_V(sev) \
307 rtc::LogCheckLevel(sev)
Tommi00aac5a2015-05-25 11:25:59 +0200308
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000309inline bool LogCheckLevel(LoggingSeverity sev) {
310 return (LogMessage::GetMinLogSeverity() <= sev);
311}
312
313#define LOG_E(sev, ctx, err, ...) \
314 LOG_SEVERITY_PRECONDITION(rtc::sev) \
315 rtc::LogMessage(__FILE__, __LINE__, rtc::sev, \
316 rtc::ERRCTX_ ## ctx, err , ##__VA_ARGS__) \
317 .stream()
318
319#define LOG_T(sev) LOG(sev) << this << ": "
320
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000321#define LOG_ERRNO_EX(sev, err) \
322 LOG_E(sev, ERRNO, err)
323#define LOG_ERRNO(sev) \
324 LOG_ERRNO_EX(sev, errno)
325
326#if defined(WEBRTC_WIN)
327#define LOG_GLE_EX(sev, err) \
328 LOG_E(sev, HRESULT, err)
329#define LOG_GLE(sev) \
330 LOG_GLE_EX(sev, GetLastError())
331#define LOG_GLEM(sev, mod) \
332 LOG_E(sev, HRESULT, GetLastError(), mod)
333#define LOG_ERR_EX(sev, err) \
334 LOG_GLE_EX(sev, err)
335#define LOG_ERR(sev) \
336 LOG_GLE(sev)
337#define LAST_SYSTEM_ERROR \
338 (::GetLastError())
339#elif __native_client__
340#define LOG_ERR_EX(sev, err) \
341 LOG(sev)
342#define LOG_ERR(sev) \
343 LOG(sev)
344#define LAST_SYSTEM_ERROR \
345 (0)
346#elif defined(WEBRTC_POSIX)
347#define LOG_ERR_EX(sev, err) \
348 LOG_ERRNO_EX(sev, err)
349#define LOG_ERR(sev) \
350 LOG_ERRNO(sev)
351#define LAST_SYSTEM_ERROR \
352 (errno)
Tommi0eefb4d2015-05-23 09:54:07 +0200353#endif // WEBRTC_WIN
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000354
jiayl66f0da22015-09-14 15:06:39 -0700355#define LOG_TAG(sev, tag) \
356 LOG_SEVERITY_PRECONDITION(sev) \
Alex Glaznevebed24d2015-09-15 11:05:24 -0700357 rtc::LogMessage(NULL, 0, sev, tag).stream()
jiayl66f0da22015-09-14 15:06:39 -0700358
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000359#define PLOG(sev, err) \
360 LOG_ERR_EX(sev, err)
361
362// TODO(?): Add an "assert" wrapper that logs in the same manner.
363
364#endif // LOG
365
366} // namespace rtc
367
368#endif // WEBRTC_BASE_LOGGING_H_