• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
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,
13 // or any LogSink.
14 //   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 
58 #include "webrtc/base/basictypes.h"
59 #include "webrtc/base/constructormagic.h"
60 #include "webrtc/base/thread_annotations.h"
61 
62 namespace rtc {
63 
64 ///////////////////////////////////////////////////////////////////////////////
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 
79 struct 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 
84 const char* FindLabel(int value, const ConstantLabel entries[]);
85 std::string ErrorName(int err, const ConstantLabel* err_table);
86 
87 //////////////////////////////////////////////////////////////////////
88 
89 // Note that the non-standard LoggingSeverity aliases exist because they are
90 // still in broad use.  The meanings of the levels are:
91 //  LS_SENSITIVE: Information which should only be logged with the consent
92 //   of the user, due to privacy concerns.
93 //  LS_VERBOSE: This level is for data which we do not want to appear in the
94 //   normal debug log, but should appear in diagnostic logs.
95 //  LS_INFO: Chatty level used in debugging for all sorts of things, the default
96 //   in debug builds.
97 //  LS_WARNING: Something that may warrant investigation.
98 //  LS_ERROR: Something that should not have occurred.
99 //  LS_NONE: Don't log.
100 enum LoggingSeverity {
101   LS_SENSITIVE,
102   LS_VERBOSE,
103   LS_INFO,
104   LS_WARNING,
105   LS_ERROR,
106   LS_NONE,
107   INFO = LS_INFO,
108   WARNING = LS_WARNING,
109   LERROR = LS_ERROR
110 };
111 
112 // LogErrorContext assists in interpreting the meaning of an error value.
113 enum LogErrorContext {
114   ERRCTX_NONE,
115   ERRCTX_ERRNO,     // System-local errno
116   ERRCTX_HRESULT,   // Windows HRESULT
117   ERRCTX_OSSTATUS,  // MacOS OSStatus
118 
119   // Abbreviations for LOG_E macro
120   ERRCTX_EN = ERRCTX_ERRNO,     // LOG_E(sev, EN, x)
121   ERRCTX_HR = ERRCTX_HRESULT,   // LOG_E(sev, HR, x)
122   ERRCTX_OS = ERRCTX_OSSTATUS,  // LOG_E(sev, OS, x)
123 };
124 
125 // Virtual sink interface that can receive log messages.
126 class LogSink {
127  public:
LogSink()128   LogSink() {}
~LogSink()129   virtual ~LogSink() {}
130   virtual void OnLogMessage(const std::string& message) = 0;
131 };
132 
133 class LogMessage {
134  public:
135   LogMessage(const char* file, int line, LoggingSeverity sev,
136              LogErrorContext err_ctx = ERRCTX_NONE, int err = 0,
137              const char* module = NULL);
138 
139   LogMessage(const char* file,
140              int line,
141              LoggingSeverity sev,
142              const std::string& tag);
143 
144   ~LogMessage();
145 
Loggable(LoggingSeverity sev)146   static inline bool Loggable(LoggingSeverity sev) { return (sev >= min_sev_); }
stream()147   std::ostream& stream() { return print_stream_; }
148 
149   // Returns the time at which this function was called for the first time.
150   // The time will be used as the logging start time.
151   // If this is not called externally, the LogMessage ctor also calls it, in
152   // which case the logging start time will be the time of the first LogMessage
153   // instance is created.
154   static uint32_t LogStartTime();
155 
156   // Returns the wall clock equivalent of |LogStartTime|, in seconds from the
157   // epoch.
158   static uint32_t WallClockStartTime();
159 
160   //  LogThreads: Display the thread identifier of the current thread
161   static void LogThreads(bool on = true);
162 
163   //  LogTimestamps: Display the elapsed time of the program
164   static void LogTimestamps(bool on = true);
165 
166   // These are the available logging channels
167   //  Debug: Debug console on Windows, otherwise stderr
168   static void LogToDebug(LoggingSeverity min_sev);
GetLogToDebug()169   static LoggingSeverity GetLogToDebug() { return dbg_sev_; }
170 
171   // Sets whether logs will be directed to stderr in debug mode.
172   static void SetLogToStderr(bool log_to_stderr);
173 
174   //  Stream: Any non-blocking stream interface.  LogMessage takes ownership of
175   //   the stream. Multiple streams may be specified by using AddLogToStream.
176   //   LogToStream is retained for backwards compatibility; when invoked, it
177   //   will discard any previously set streams and install the specified stream.
178   //   GetLogToStream gets the severity for the specified stream, of if none
179   //   is specified, the minimum stream severity.
180   //   RemoveLogToStream removes the specified stream, without destroying it.
181   static int GetLogToStream(LogSink* stream = NULL);
182   static void AddLogToStream(LogSink* stream, LoggingSeverity min_sev);
183   static void RemoveLogToStream(LogSink* stream);
184 
185   // Testing against MinLogSeverity allows code to avoid potentially expensive
186   // logging operations by pre-checking the logging level.
GetMinLogSeverity()187   static int GetMinLogSeverity() { return min_sev_; }
188 
189   // Parses the provided parameter stream to configure the options above.
190   // Useful for configuring logging from the command line.
191   static void ConfigureLogging(const char* params);
192 
193  private:
194   typedef std::pair<LogSink*, LoggingSeverity> StreamAndSeverity;
195   typedef std::list<StreamAndSeverity> StreamList;
196 
197   // Updates min_sev_ appropriately when debug sinks change.
198   static void UpdateMinLogSeverity();
199 
200   // These write out the actual log messages.
201   static void OutputToDebug(const std::string& msg,
202                             LoggingSeverity severity,
203                             const std::string& tag);
204 
205   // The ostream that buffers the formatted message before output
206   std::ostringstream print_stream_;
207 
208   // The severity level of this message
209   LoggingSeverity severity_;
210 
211   // The Android debug output tag.
212   std::string tag_;
213 
214   // String data generated in the constructor, that should be appended to
215   // the message before output.
216   std::string extra_;
217 
218   // dbg_sev_ is the thresholds for those output targets
219   // min_sev_ is the minimum (most verbose) of those levels, and is used
220   //  as a short-circuit in the logging macros to identify messages that won't
221   //  be logged.
222   // ctx_sev_ is the minimum level at which file context is displayed
223   static LoggingSeverity min_sev_, dbg_sev_, ctx_sev_;
224 
225   // The output streams and their associated severities
226   static StreamList streams_;
227 
228   // Flags for formatting options
229   static bool thread_, timestamp_;
230 
231   // Determines if logs will be directed to stderr in debug mode.
232   static bool log_to_stderr_;
233 
234   RTC_DISALLOW_COPY_AND_ASSIGN(LogMessage);
235 };
236 
237 //////////////////////////////////////////////////////////////////////
238 // Logging Helpers
239 //////////////////////////////////////////////////////////////////////
240 
241 class LogMultilineState {
242  public:
243   size_t unprintable_count_[2];
LogMultilineState()244   LogMultilineState() {
245     unprintable_count_[0] = unprintable_count_[1] = 0;
246   }
247 };
248 
249 // When possible, pass optional state variable to track various data across
250 // multiple calls to LogMultiline.  Otherwise, pass NULL.
251 void LogMultiline(LoggingSeverity level, const char* label, bool input,
252                   const void* data, size_t len, bool hex_mode,
253                   LogMultilineState* state);
254 
255 #ifndef LOG
256 
257 // The following non-obvious technique for implementation of a
258 // conditional log stream was stolen from google3/base/logging.h.
259 
260 // This class is used to explicitly ignore values in the conditional
261 // logging macros.  This avoids compiler warnings like "value computed
262 // is not used" and "statement has no effect".
263 
264 class LogMessageVoidify {
265  public:
LogMessageVoidify()266   LogMessageVoidify() { }
267   // This has to be an operator with a precedence lower than << but
268   // higher than ?:
269   void operator&(std::ostream&) { }
270 };
271 
272 #define LOG_SEVERITY_PRECONDITION(sev) \
273   !(rtc::LogMessage::Loggable(sev)) \
274     ? (void) 0 \
275     : rtc::LogMessageVoidify() &
276 
277 #define LOG(sev) \
278   LOG_SEVERITY_PRECONDITION(rtc::sev) \
279     rtc::LogMessage(__FILE__, __LINE__, rtc::sev).stream()
280 
281 // The _V version is for when a variable is passed in.  It doesn't do the
282 // namespace concatination.
283 #define LOG_V(sev) \
284   LOG_SEVERITY_PRECONDITION(sev) \
285     rtc::LogMessage(__FILE__, __LINE__, sev).stream()
286 
287 // The _F version prefixes the message with the current function name.
288 #if (defined(__GNUC__) && !defined(NDEBUG)) || defined(WANT_PRETTY_LOG_F)
289 #define LOG_F(sev) LOG(sev) << __PRETTY_FUNCTION__ << ": "
290 #define LOG_T_F(sev) LOG(sev) << this << ": " << __PRETTY_FUNCTION__ << ": "
291 #else
292 #define LOG_F(sev) LOG(sev) << __FUNCTION__ << ": "
293 #define LOG_T_F(sev) LOG(sev) << this << ": " << __FUNCTION__ << ": "
294 #endif
295 
296 #define LOG_CHECK_LEVEL(sev) \
297   rtc::LogCheckLevel(rtc::sev)
298 #define LOG_CHECK_LEVEL_V(sev) \
299   rtc::LogCheckLevel(sev)
300 
LogCheckLevel(LoggingSeverity sev)301 inline bool LogCheckLevel(LoggingSeverity sev) {
302   return (LogMessage::GetMinLogSeverity() <= sev);
303 }
304 
305 #define LOG_E(sev, ctx, err, ...) \
306   LOG_SEVERITY_PRECONDITION(rtc::sev) \
307     rtc::LogMessage(__FILE__, __LINE__, rtc::sev, \
308                           rtc::ERRCTX_ ## ctx, err , ##__VA_ARGS__) \
309         .stream()
310 
311 #define LOG_T(sev) LOG(sev) << this << ": "
312 
313 #define LOG_ERRNO_EX(sev, err) \
314   LOG_E(sev, ERRNO, err)
315 #define LOG_ERRNO(sev) \
316   LOG_ERRNO_EX(sev, errno)
317 
318 #if defined(WEBRTC_WIN)
319 #define LOG_GLE_EX(sev, err) \
320   LOG_E(sev, HRESULT, err)
321 #define LOG_GLE(sev) \
322   LOG_GLE_EX(sev, GetLastError())
323 #define LOG_GLEM(sev, mod) \
324   LOG_E(sev, HRESULT, GetLastError(), mod)
325 #define LOG_ERR_EX(sev, err) \
326   LOG_GLE_EX(sev, err)
327 #define LOG_ERR(sev) \
328   LOG_GLE(sev)
329 #define LAST_SYSTEM_ERROR \
330   (::GetLastError())
331 #elif __native_client__
332 #define LOG_ERR_EX(sev, err) \
333   LOG(sev)
334 #define LOG_ERR(sev) \
335   LOG(sev)
336 #define LAST_SYSTEM_ERROR \
337   (0)
338 #elif defined(WEBRTC_POSIX)
339 #define LOG_ERR_EX(sev, err) \
340   LOG_ERRNO_EX(sev, err)
341 #define LOG_ERR(sev) \
342   LOG_ERRNO(sev)
343 #define LAST_SYSTEM_ERROR \
344   (errno)
345 #endif  // WEBRTC_WIN
346 
347 #define LOG_TAG(sev, tag) \
348   LOG_SEVERITY_PRECONDITION(sev) \
349     rtc::LogMessage(NULL, 0, sev, tag).stream()
350 
351 #define PLOG(sev, err) \
352   LOG_ERR_EX(sev, err)
353 
354 // TODO(?): Add an "assert" wrapper that logs in the same manner.
355 
356 #endif  // LOG
357 
358 }  // namespace rtc
359 
360 #endif  // WEBRTC_BASE_LOGGING_H_
361