~ubuntu-branches/debian/experimental/kopete/experimental

« back to all changes in this revision

Viewing changes to protocols/jabber/libjingle/talk/base/logging.h

  • Committer: Package Import Robot
  • Author(s): Maximiliano Curia
  • Date: 2015-02-24 11:32:57 UTC
  • mfrom: (1.1.41 vivid)
  • Revision ID: package-import@ubuntu.com-20150224113257-gnupg4v7lzz18ij0
Tags: 4:14.12.2-1
* New upstream release (14.12.2).
* Bump Standards-Version to 3.9.6, no changes needed.

Show diffs side-by-side

added added

removed removed

Lines of Context:
 
1
/*
 
2
 * libjingle
 
3
 * Copyright 2004--2005, Google Inc.
 
4
 *
 
5
 * Redistribution and use in source and binary forms, with or without
 
6
 * modification, are permitted provided that the following conditions are met:
 
7
 *
 
8
 *  1. Redistributions of source code must retain the above copyright notice,
 
9
 *     this list of conditions and the following disclaimer.
 
10
 *  2. Redistributions in binary form must reproduce the above copyright notice,
 
11
 *     this list of conditions and the following disclaimer in the documentation
 
12
 *     and/or other materials provided with the distribution.
 
13
 *  3. The name of the author may not be used to endorse or promote products
 
14
 *     derived from this software without specific prior written permission.
 
15
 *
 
16
 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED
 
17
 * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
 
18
 * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO
 
19
 * EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
 
20
 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
 
21
 * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;
 
22
 * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
 
23
 * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
 
24
 * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
 
25
 * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 
26
 */
 
27
 
 
28
//   LOG(...) an ostream target that can be used to send formatted
 
29
// output to a variety of logging targets, such as debugger console, stderr,
 
30
// file, or any StreamInterface.
 
31
//   The severity level passed as the first argument to the LOGging
 
32
// functions is used as a filter, to limit the verbosity of the logging.
 
33
//   Static members of LogMessage documented below are used to control the
 
34
// verbosity and target of the output.
 
35
//   There are several variations on the LOG macro which facilitate logging
 
36
// of common error conditions, detailed below.
 
37
 
 
38
// LOG(sev) logs the given stream at severity "sev", which must be a
 
39
//     compile-time constant of the LoggingSeverity type, without the namespace
 
40
//     prefix.
 
41
// LOG_V(sev) Like LOG(), but sev is a run-time variable of the LoggingSeverity
 
42
//     type (basically, it just doesn't prepend the namespace).
 
43
// LOG_F(sev) Like LOG(), but includes the name of the current function.
 
44
// LOG_GLE(M)(sev [, mod]) attempt to add a string description of the
 
45
//     HRESULT returned by GetLastError.  The "M" variant allows searching of a
 
46
//     DLL's string table for the error description.
 
47
// LOG_ERRNO(sev) attempts to add a string description of an errno-derived
 
48
//     error. errno and associated facilities exist on both Windows and POSIX,
 
49
//     but on Windows they only apply to the C/C++ runtime.
 
50
// LOG_ERR(sev) is an alias for the platform's normal error system, i.e. _GLE on
 
51
//     Windows and _ERRNO on POSIX.
 
52
// (The above three also all have _EX versions that let you specify the error
 
53
// code, rather than using the last one.)
 
54
// LOG_E(sev, ctx, err, ...) logs a detailed error interpreted using the
 
55
//     specified context.
 
56
// LOG_CHECK_LEVEL(sev) (and LOG_CHECK_LEVEL_V(sev)) can be used as a test
 
57
//     before performing expensive or sensitive operations whose sole purpose is
 
58
//     to output logging data at the desired level.
 
59
// Lastly, PLOG(sev, err) is an alias for LOG_ERR_EX.
 
60
 
 
61
#ifndef TALK_BASE_LOGGING_H_
 
62
#define TALK_BASE_LOGGING_H_
 
63
 
 
64
#ifdef HAVE_CONFIG_H
 
65
#include "config.h"  // NOLINT
 
66
#endif
 
67
 
 
68
#include <list>
 
69
#include <sstream>
 
70
#include <string>
 
71
#include <utility>
 
72
#include "talk/base/basictypes.h"
 
73
#include "talk/base/criticalsection.h"
 
74
 
 
75
namespace talk_base {
 
76
 
 
77
class StreamInterface;
 
78
 
 
79
///////////////////////////////////////////////////////////////////////////////
 
80
// ConstantLabel can be used to easily generate string names from constant
 
81
// values.  This can be useful for logging descriptive names of error messages.
 
82
// Usage:
 
83
//   const ConstantLabel LIBRARY_ERRORS[] = {
 
84
//     KLABEL(SOME_ERROR),
 
85
//     KLABEL(SOME_OTHER_ERROR),
 
86
//     ...
 
87
//     LASTLABEL
 
88
//   }
 
89
//
 
90
//   int err = LibraryFunc();
 
91
//   LOG(LS_ERROR) << "LibraryFunc returned: "
 
92
//                 << ErrorName(err, LIBRARY_ERRORS);
 
93
 
 
94
struct ConstantLabel { int value; const char * label; };
 
95
#define KLABEL(x) { x, #x }
 
96
#define TLABEL(x, y) { x, y }
 
97
#define LASTLABEL { 0, 0 }
 
98
 
 
99
const char * FindLabel(int value, const ConstantLabel entries[]);
 
100
std::string ErrorName(int err, const ConstantLabel* err_table);
 
101
 
 
102
//////////////////////////////////////////////////////////////////////
 
103
 
 
104
// Note that the non-standard LoggingSeverity aliases exist because they are
 
105
// still in broad use.  The meanings of the levels are:
 
106
//  LS_SENSITIVE: Information which should only be logged with the consent
 
107
//   of the user, due to privacy concerns.
 
108
//  LS_VERBOSE: This level is for data which we do not want to appear in the
 
109
//   normal debug log, but should appear in diagnostic logs.
 
110
//  LS_INFO: Chatty level used in debugging for all sorts of things, the default
 
111
//   in debug builds.
 
112
//  LS_WARNING: Something that may warrant investigation.
 
113
//  LS_ERROR: Something that should not have occurred.
 
114
enum LoggingSeverity { LS_SENSITIVE, LS_VERBOSE, LS_INFO, LS_WARNING, LS_ERROR,
 
115
                       INFO = LS_INFO,
 
116
                       WARNING = LS_WARNING,
 
117
                       LERROR = LS_ERROR };
 
118
 
 
119
// LogErrorContext assists in interpreting the meaning of an error value.
 
120
enum LogErrorContext {
 
121
  ERRCTX_NONE,
 
122
  ERRCTX_ERRNO,     // System-local errno
 
123
  ERRCTX_HRESULT,   // Windows HRESULT
 
124
  ERRCTX_OSSTATUS,  // MacOS OSStatus
 
125
 
 
126
  // Abbreviations for LOG_E macro
 
127
  ERRCTX_EN = ERRCTX_ERRNO,     // LOG_E(sev, EN, x)
 
128
  ERRCTX_HR = ERRCTX_HRESULT,   // LOG_E(sev, HR, x)
 
129
  ERRCTX_OS = ERRCTX_OSSTATUS,  // LOG_E(sev, OS, x)
 
130
};
 
131
 
 
132
class LogMessage {
 
133
 public:
 
134
  static const int NO_LOGGING;
 
135
 
 
136
  LogMessage(const char* file, int line, LoggingSeverity sev,
 
137
             LogErrorContext err_ctx = ERRCTX_NONE, int err = 0,
 
138
             const char* module = NULL);
 
139
  ~LogMessage();
 
140
 
 
141
  static inline bool Loggable(LoggingSeverity sev) { return (sev >= min_sev_); }
 
142
  std::ostream& stream() { return print_stream_; }
 
143
 
 
144
  // Returns the time at which this function was called for the first time.
 
145
  // The time will be used as the logging start time.
 
146
  // If this is not called externally, the LogMessage ctor also calls it, in
 
147
  // which case the logging start time will be the time of the first LogMessage
 
148
  // instance is created.
 
149
  static uint32 LogStartTime();
 
150
 
 
151
  // These are attributes which apply to all logging channels
 
152
  //  LogContext: Display the file and line number of the message
 
153
  static void LogContext(int min_sev);
 
154
  //  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
 
161
  static void LogToDebug(int min_sev);
 
162
  static int GetLogToDebug() { return dbg_sev_; }
 
163
 
 
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.
 
171
  static void LogToStream(StreamInterface* stream, int min_sev);
 
172
  static int GetLogToStream(StreamInterface* stream = NULL);
 
173
  static void AddLogToStream(StreamInterface* stream, int min_sev);
 
174
  static void RemoveLogToStream(StreamInterface* stream);
 
175
 
 
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.
 
184
  // Useful for configuring logging from the command line.  If file logging
 
185
  // is enabled, it is output to the specified filename.
 
186
  static void ConfigureLogging(const char* params, const char* filename);
 
187
 
 
188
  // Convert the string to a LS_ value; also accept numeric values.
 
189
  static int ParseLogSeverity(const std::string& value);
 
190
 
 
191
 private:
 
192
  typedef std::list<std::pair<StreamInterface*, int> > StreamList;
 
193
 
 
194
  // Updates min_sev_ appropriately when debug sinks change.
 
195
  static void UpdateMinLogSeverity();
 
196
 
 
197
  // These assist in formatting some parts of the debug output.
 
198
  static const char* Describe(LoggingSeverity sev);
 
199
  static const char* DescribeFile(const char* file);
 
200
 
 
201
  // These write out the actual log messages.
 
202
  static void OutputToDebug(const std::string& msg, LoggingSeverity severity_);
 
203
  static void OutputToStream(StreamInterface* stream, const std::string& msg);
 
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
  // String data generated in the constructor, that should be appended to
 
212
  // the message before output.
 
213
  std::string extra_;
 
214
 
 
215
  // Global lock for the logging subsystem
 
216
  static CriticalSection crit_;
 
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 int 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
  // are we in diagnostic mode (as defined by the app)?
 
232
  static bool is_diagnostic_mode_;
 
233
 
 
234
  DISALLOW_EVIL_CONSTRUCTORS(LogMessage);
 
235
};
 
236
 
 
237
//////////////////////////////////////////////////////////////////////
 
238
// Logging Helpers
 
239
//////////////////////////////////////////////////////////////////////
 
240
 
 
241
class LogMultilineState {
 
242
 public:
 
243
  size_t unprintable_count_[2];
 
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
//////////////////////////////////////////////////////////////////////
 
256
// Macros which automatically disable logging when LOGGING == 0
 
257
//////////////////////////////////////////////////////////////////////
 
258
 
 
259
// If LOGGING is not explicitly defined, default to enabled in debug mode
 
260
#if !defined(LOGGING)
 
261
#if defined(_DEBUG) && !defined(NDEBUG)
 
262
#define LOGGING 1
 
263
#else
 
264
#define LOGGING 0
 
265
#endif
 
266
#endif  // !defined(LOGGING)
 
267
 
 
268
#ifndef LOG
 
269
#if LOGGING
 
270
 
 
271
// The following non-obvious technique for implementation of a
 
272
// conditional log stream was stolen from google3/base/logging.h.
 
273
 
 
274
// This class is used to explicitly ignore values in the conditional
 
275
// logging macros.  This avoids compiler warnings like "value computed
 
276
// is not used" and "statement has no effect".
 
277
 
 
278
class LogMessageVoidify {
 
279
 public:
 
280
  LogMessageVoidify() { }
 
281
  // This has to be an operator with a precedence lower than << but
 
282
  // higher than ?:
 
283
  void operator&(std::ostream&) { }
 
284
};
 
285
 
 
286
#define LOG_SEVERITY_PRECONDITION(sev) \
 
287
  !(talk_base::LogMessage::Loggable(sev)) \
 
288
    ? (void) 0 \
 
289
    : talk_base::LogMessageVoidify() &
 
290
 
 
291
#define LOG(sev) \
 
292
  LOG_SEVERITY_PRECONDITION(talk_base::sev) \
 
293
    talk_base::LogMessage(__FILE__, __LINE__, talk_base::sev).stream()
 
294
 
 
295
// The _V version is for when a variable is passed in.  It doesn't do the
 
296
// namespace concatination.
 
297
#define LOG_V(sev) \
 
298
  LOG_SEVERITY_PRECONDITION(sev) \
 
299
    talk_base::LogMessage(__FILE__, __LINE__, sev).stream()
 
300
 
 
301
// The _F version prefixes the message with the current function name.
 
302
#if (defined(__GNUC__) && defined(_DEBUG)) || defined(WANT_PRETTY_LOG_F)
 
303
#define LOG_F(sev) LOG(sev) << __PRETTY_FUNCTION__ << ": "
 
304
#else
 
305
#define LOG_F(sev) LOG(sev) << __FUNCTION__ << ": "
 
306
#endif
 
307
 
 
308
#define LOG_CHECK_LEVEL(sev) \
 
309
  talk_base::LogCheckLevel(talk_base::sev)
 
310
#define LOG_CHECK_LEVEL_V(sev) \
 
311
  talk_base::LogCheckLevel(sev)
 
312
inline bool LogCheckLevel(LoggingSeverity sev) {
 
313
  return (LogMessage::GetMinLogSeverity() <= sev);
 
314
}
 
315
 
 
316
#define LOG_E(sev, ctx, err, ...) \
 
317
  LOG_SEVERITY_PRECONDITION(talk_base::sev) \
 
318
    talk_base::LogMessage(__FILE__, __LINE__, talk_base::sev, \
 
319
                          talk_base::ERRCTX_ ## ctx, err , ##__VA_ARGS__) \
 
320
        .stream()
 
321
 
 
322
#else  // !LOGGING
 
323
 
 
324
// Hopefully, the compiler will optimize away some of this code.
 
325
// Note: syntax of "1 ? (void)0 : LogMessage" was causing errors in g++,
 
326
//   converted to "while (false)"
 
327
#define LOG(sev) \
 
328
  while (false)talk_base:: LogMessage(NULL, 0, talk_base::sev).stream()
 
329
#define LOG_V(sev) \
 
330
  while (false) talk_base::LogMessage(NULL, 0, sev).stream()
 
331
#define LOG_F(sev) LOG(sev) << __FUNCTION__ << ": "
 
332
#define LOG_CHECK_LEVEL(sev) \
 
333
  false
 
334
#define LOG_CHECK_LEVEL_V(sev) \
 
335
  false
 
336
 
 
337
#define LOG_E(sev, ctx, err, ...) \
 
338
  while (false) talk_base::LogMessage(__FILE__, __LINE__, talk_base::sev, \
 
339
                          talk_base::ERRCTX_ ## ctx, err , ##__VA_ARGS__) \
 
340
      .stream()
 
341
 
 
342
#endif  // !LOGGING
 
343
 
 
344
#define LOG_ERRNO_EX(sev, err) \
 
345
  LOG_E(sev, ERRNO, err)
 
346
#define LOG_ERRNO(sev) \
 
347
  LOG_ERRNO_EX(sev, errno)
 
348
 
 
349
#ifdef WIN32
 
350
#define LOG_GLE_EX(sev, err) \
 
351
  LOG_E(sev, HRESULT, err)
 
352
#define LOG_GLE(sev) \
 
353
  LOG_GLE_EX(sev, GetLastError())
 
354
#define LOG_GLEM(sev, mod) \
 
355
  LOG_E(sev, HRESULT, GetLastError(), mod)
 
356
#define LOG_ERR_EX(sev, err) \
 
357
  LOG_GLE_EX(sev, err)
 
358
#define LOG_ERR(sev) \
 
359
  LOG_GLE(sev)
 
360
#define LAST_SYSTEM_ERROR \
 
361
  (::GetLastError())
 
362
#elif POSIX
 
363
#define LOG_ERR_EX(sev, err) \
 
364
  LOG_ERRNO_EX(sev, err)
 
365
#define LOG_ERR(sev) \
 
366
  LOG_ERRNO(sev)
 
367
#define LAST_SYSTEM_ERROR \
 
368
  (errno)
 
369
#endif  // WIN32
 
370
 
 
371
#define PLOG(sev, err) \
 
372
  LOG_ERR_EX(sev, err)
 
373
 
 
374
// TODO(?): Add an "assert" wrapper that logs in the same manner.
 
375
 
 
376
#endif  // LOG
 
377
 
 
378
}  // namespace talk_base
 
379
 
 
380
#endif  // TALK_BASE_LOGGING_H_