blob: 2fb6f3ee7dcd7efc666332e33f29280eff532beb [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"
59
60namespace rtc {
61
henrike@webrtc.orgf0488722014-05-13 18:00:26 +000062///////////////////////////////////////////////////////////////////////////////
63// ConstantLabel can be used to easily generate string names from constant
64// values. This can be useful for logging descriptive names of error messages.
65// Usage:
66// const ConstantLabel LIBRARY_ERRORS[] = {
67// KLABEL(SOME_ERROR),
68// KLABEL(SOME_OTHER_ERROR),
69// ...
70// LASTLABEL
71// }
72//
73// int err = LibraryFunc();
74// LOG(LS_ERROR) << "LibraryFunc returned: "
75// << ErrorName(err, LIBRARY_ERRORS);
76
77struct ConstantLabel { int value; const char * label; };
78#define KLABEL(x) { x, #x }
79#define TLABEL(x, y) { x, y }
80#define LASTLABEL { 0, 0 }
81
82const char * FindLabel(int value, const ConstantLabel entries[]);
83std::string ErrorName(int err, const ConstantLabel* err_table);
84
85//////////////////////////////////////////////////////////////////////
86
87// Note that the non-standard LoggingSeverity aliases exist because they are
88// still in broad use. The meanings of the levels are:
89// LS_SENSITIVE: Information which should only be logged with the consent
90// of the user, due to privacy concerns.
91// LS_VERBOSE: This level is for data which we do not want to appear in the
92// normal debug log, but should appear in diagnostic logs.
93// LS_INFO: Chatty level used in debugging for all sorts of things, the default
94// in debug builds.
95// LS_WARNING: Something that may warrant investigation.
96// LS_ERROR: Something that should not have occurred.
Tommi0eefb4d2015-05-23 09:54:07 +020097// LS_NONE: Don't log.
98enum LoggingSeverity {
99 LS_SENSITIVE,
100 LS_VERBOSE,
101 LS_INFO,
102 LS_WARNING,
103 LS_ERROR,
104 LS_NONE,
105 INFO = LS_INFO,
106 WARNING = LS_WARNING,
107 LERROR = LS_ERROR
108};
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000109
110// LogErrorContext assists in interpreting the meaning of an error value.
111enum LogErrorContext {
112 ERRCTX_NONE,
113 ERRCTX_ERRNO, // System-local errno
114 ERRCTX_HRESULT, // Windows HRESULT
115 ERRCTX_OSSTATUS, // MacOS OSStatus
116
117 // Abbreviations for LOG_E macro
118 ERRCTX_EN = ERRCTX_ERRNO, // LOG_E(sev, EN, x)
119 ERRCTX_HR = ERRCTX_HRESULT, // LOG_E(sev, HR, x)
120 ERRCTX_OS = ERRCTX_OSSTATUS, // LOG_E(sev, OS, x)
121};
122
Tommi0eefb4d2015-05-23 09:54:07 +0200123// Virtual sink interface that can receive log messages.
124class LogSink {
125 public:
126 LogSink() {}
127 virtual ~LogSink() {}
128 virtual void OnLogMessage(const std::string& message) = 0;
129};
130
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000131class LogMessage {
132 public:
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000133 static const uint32 WARN_SLOW_LOGS_DELAY = 50; // ms
134
135 LogMessage(const char* file, int line, LoggingSeverity sev,
136 LogErrorContext err_ctx = ERRCTX_NONE, int err = 0,
137 const char* module = NULL);
138 ~LogMessage();
139
140 static inline bool Loggable(LoggingSeverity sev) { return (sev >= min_sev_); }
141 std::ostream& stream() { return print_stream_; }
142
143 // Returns the time at which this function was called for the first time.
144 // The time will be used as the logging start time.
145 // If this is not called externally, the LogMessage ctor also calls it, in
146 // which case the logging start time will be the time of the first LogMessage
147 // instance is created.
148 static uint32 LogStartTime();
149
150 // Returns the wall clock equivalent of |LogStartTime|, in seconds from the
151 // epoch.
152 static uint32 WallClockStartTime();
153
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000154 // LogThreads: Display the thread identifier of the current thread
155 static void LogThreads(bool on = true);
156 // LogTimestamps: Display the elapsed time of the program
157 static void LogTimestamps(bool on = true);
158
159 // These are the available logging channels
160 // Debug: Debug console on Windows, otherwise stderr
Tommi0eefb4d2015-05-23 09:54:07 +0200161 static void LogToDebug(LoggingSeverity min_sev);
162 static LoggingSeverity GetLogToDebug() { return dbg_sev_; }
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000163
164 // Stream: Any non-blocking stream interface. LogMessage takes ownership of
165 // the stream. Multiple streams may be specified by using AddLogToStream.
166 // LogToStream is retained for backwards compatibility; when invoked, it
167 // will discard any previously set streams and install the specified stream.
168 // GetLogToStream gets the severity for the specified stream, of if none
169 // is specified, the minimum stream severity.
170 // RemoveLogToStream removes the specified stream, without destroying it.
Tommi0eefb4d2015-05-23 09:54:07 +0200171 static void LogToStream(LogSink* stream, LoggingSeverity min_sev);
172 static int GetLogToStream(LogSink* stream = NULL);
173 static void AddLogToStream(LogSink* stream, LoggingSeverity min_sev);
174 static void RemoveLogToStream(LogSink* stream);
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000175
176 // Testing against MinLogSeverity allows code to avoid potentially expensive
177 // logging operations by pre-checking the logging level.
178 static int GetMinLogSeverity() { return min_sev_; }
179
180 static void SetDiagnosticMode(bool f) { is_diagnostic_mode_ = f; }
181 static bool IsDiagnosticMode() { return is_diagnostic_mode_; }
182
183 // Parses the provided parameter stream to configure the options above.
Tommi0eefb4d2015-05-23 09:54:07 +0200184 // Useful for configuring logging from the command line.
185 static void ConfigureLogging(const char* params);
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000186
187 private:
Tommi0eefb4d2015-05-23 09:54:07 +0200188 typedef std::pair<LogSink*, LoggingSeverity> StreamAndSeverity;
189 typedef std::list<StreamAndSeverity> StreamList;
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000190
191 // Updates min_sev_ appropriately when debug sinks change.
192 static void UpdateMinLogSeverity();
193
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000194 // These write out the actual log messages.
195 static void OutputToDebug(const std::string& msg, LoggingSeverity severity_);
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000196
197 // The ostream that buffers the formatted message before output
198 std::ostringstream print_stream_;
199
200 // The severity level of this message
201 LoggingSeverity severity_;
202
203 // String data generated in the constructor, that should be appended to
204 // the message before output.
205 std::string extra_;
206
207 // If time it takes to write to stream is more than this, log one
208 // additional warning about it.
209 uint32 warn_slow_logs_delay_;
210
211 // Global lock for the logging subsystem
212 static CriticalSection crit_;
213
214 // 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
227 // are we in diagnostic mode (as defined by the app)?
228 static bool is_diagnostic_mode_;
229
Thiago Farinaae0f0ee2015-04-04 23:56:53 +0000230 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.
284#if (defined(__GNUC__) && defined(_DEBUG)) || defined(WANT_PRETTY_LOG_F)
285#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)
296inline bool LogCheckLevel(LoggingSeverity sev) {
297 return (LogMessage::GetMinLogSeverity() <= sev);
298}
299
300#define LOG_E(sev, ctx, err, ...) \
301 LOG_SEVERITY_PRECONDITION(rtc::sev) \
302 rtc::LogMessage(__FILE__, __LINE__, rtc::sev, \
303 rtc::ERRCTX_ ## ctx, err , ##__VA_ARGS__) \
304 .stream()
305
306#define LOG_T(sev) LOG(sev) << this << ": "
307
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000308#define LOG_ERRNO_EX(sev, err) \
309 LOG_E(sev, ERRNO, err)
310#define LOG_ERRNO(sev) \
311 LOG_ERRNO_EX(sev, errno)
312
313#if defined(WEBRTC_WIN)
314#define LOG_GLE_EX(sev, err) \
315 LOG_E(sev, HRESULT, err)
316#define LOG_GLE(sev) \
317 LOG_GLE_EX(sev, GetLastError())
318#define LOG_GLEM(sev, mod) \
319 LOG_E(sev, HRESULT, GetLastError(), mod)
320#define LOG_ERR_EX(sev, err) \
321 LOG_GLE_EX(sev, err)
322#define LOG_ERR(sev) \
323 LOG_GLE(sev)
324#define LAST_SYSTEM_ERROR \
325 (::GetLastError())
326#elif __native_client__
327#define LOG_ERR_EX(sev, err) \
328 LOG(sev)
329#define LOG_ERR(sev) \
330 LOG(sev)
331#define LAST_SYSTEM_ERROR \
332 (0)
333#elif defined(WEBRTC_POSIX)
334#define LOG_ERR_EX(sev, err) \
335 LOG_ERRNO_EX(sev, err)
336#define LOG_ERR(sev) \
337 LOG_ERRNO(sev)
338#define LAST_SYSTEM_ERROR \
339 (errno)
Tommi0eefb4d2015-05-23 09:54:07 +0200340#endif // WEBRTC_WIN
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000341
342#define PLOG(sev, err) \
343 LOG_ERR_EX(sev, err)
344
345// TODO(?): Add an "assert" wrapper that logs in the same manner.
346
347#endif // LOG
348
349} // namespace rtc
350
351#endif // WEBRTC_BASE_LOGGING_H_