You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

389 lines
15 KiB

​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
  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. // LOG(...) an ostream target that can be used to send formatted
  28. // output to a variety of logging targets, such as debugger console, stderr,
  29. // file, or any StreamInterface.
  30. // The severity level passed as the first argument to the LOGging
  31. // functions is used as a filter, to limit the verbosity of the logging.
  32. // Static members of LogMessage documented below are used to control the
  33. // verbosity and target of the output.
  34. // There are several variations on the LOG macro which facilitate logging
  35. // of common error conditions, detailed below.
  36. // LOG(sev) logs the given stream at severity "sev", which must be a
  37. // compile-time constant of the LoggingSeverity type, without the namespace
  38. // prefix.
  39. // LOG_V(sev) Like LOG(), but sev is a run-time variable of the LoggingSeverity
  40. // type (basically, it just doesn't prepend the namespace).
  41. // LOG_F(sev) Like LOG(), but includes the name of the current function.
  42. // LOG_GLE(M)(sev [, mod]) attempt to add a string description of the
  43. // HRESULT returned by GetLastError. The "M" variant allows searching of a
  44. // DLL's string table for the error description.
  45. // LOG_ERRNO(sev) attempts to add a string description of an errno-derived
  46. // error. errno and associated facilities exist on both Windows and POSIX,
  47. // but on Windows they only apply to the C/C++ runtime.
  48. // LOG_ERR(sev) is an alias for the platform's normal error system, i.e. _GLE on
  49. // Windows and _ERRNO on POSIX.
  50. // (The above three also all have _EX versions that let you specify the error
  51. // code, rather than using the last one.)
  52. // LOG_E(sev, ctx, err, ...) logs a detailed error interpreted using the
  53. // specified context.
  54. // LOG_CHECK_LEVEL(sev) (and LOG_CHECK_LEVEL_V(sev)) can be used as a test
  55. // before performing expensive or sensitive operations whose sole purpose is
  56. // to output logging data at the desired level.
  57. // Lastly, PLOG(sev, err) is an alias for LOG_ERR_EX.
  58. #ifndef TALK_BASE_LOGGING_H_
  59. #define TALK_BASE_LOGGING_H_
  60. #ifdef HAVE_CONFIG_H
  61. #include "config.h" // NOLINT
  62. #endif
  63. #include <list>
  64. #include <sstream>
  65. #include <string>
  66. #include <utility>
  67. #include "talk/base/basictypes.h"
  68. #include "talk/base/criticalsection.h"
  69. namespace talk_base {
  70. class StreamInterface;
  71. ///////////////////////////////////////////////////////////////////////////////
  72. // ConstantLabel can be used to easily generate string names from constant
  73. // values. This can be useful for logging descriptive names of error messages.
  74. // Usage:
  75. // const ConstantLabel LIBRARY_ERRORS[] = {
  76. // KLABEL(SOME_ERROR),
  77. // KLABEL(SOME_OTHER_ERROR),
  78. // ...
  79. // LASTLABEL
  80. // }
  81. //
  82. // int err = LibraryFunc();
  83. // LOG(LS_ERROR) << "LibraryFunc returned: "
  84. // << ErrorName(err, LIBRARY_ERRORS);
  85. struct ConstantLabel { int value; const char * label; };
  86. #define KLABEL(x) { x, #x }
  87. #define TLABEL(x, y) { x, y }
  88. #define LASTLABEL { 0, 0 }
  89. const char * FindLabel(int value, const ConstantLabel entries[]);
  90. std::string ErrorName(int err, const ConstantLabel* err_table);
  91. //////////////////////////////////////////////////////////////////////
  92. // Note that the non-standard LoggingSeverity aliases exist because they are
  93. // still in broad use. The meanings of the levels are:
  94. // LS_SENSITIVE: Information which should only be logged with the consent
  95. // of the user, due to privacy concerns.
  96. // LS_VERBOSE: This level is for data which we do not want to appear in the
  97. // normal debug log, but should appear in diagnostic logs.
  98. // LS_INFO: Chatty level used in debugging for all sorts of things, the default
  99. // in debug builds.
  100. // LS_WARNING: Something that may warrant investigation.
  101. // LS_ERROR: Something that should not have occurred.
  102. enum LoggingSeverity { LS_SENSITIVE, LS_VERBOSE, LS_INFO, LS_WARNING, LS_ERROR,
  103. INFO = LS_INFO,
  104. WARNING = LS_WARNING,
  105. LERROR = LS_ERROR };
  106. // LogErrorContext assists in interpreting the meaning of an error value.
  107. enum LogErrorContext {
  108. ERRCTX_NONE,
  109. ERRCTX_ERRNO, // System-local errno
  110. ERRCTX_HRESULT, // Windows HRESULT
  111. ERRCTX_OSSTATUS, // MacOS OSStatus
  112. // Abbreviations for LOG_E macro
  113. ERRCTX_EN = ERRCTX_ERRNO, // LOG_E(sev, EN, x)
  114. ERRCTX_HR = ERRCTX_HRESULT, // LOG_E(sev, HR, x)
  115. ERRCTX_OS = ERRCTX_OSSTATUS, // LOG_E(sev, OS, x)
  116. };
  117. class LogMessage {
  118. public:
  119. static const int NO_LOGGING;
  120. static const uint32 WARN_SLOW_LOGS_DELAY = 50; // ms
  121. LogMessage(const char* file, int line, LoggingSeverity sev,
  122. LogErrorContext err_ctx = ERRCTX_NONE, int err = 0,
  123. const char* module = NULL);
  124. ~LogMessage();
  125. static inline bool Loggable(LoggingSeverity sev) { return (sev >= min_sev_); }
  126. std::ostream& stream() { return print_stream_; }
  127. // Returns the time at which this function was called for the first time.
  128. // The time will be used as the logging start time.
  129. // If this is not called externally, the LogMessage ctor also calls it, in
  130. // which case the logging start time will be the time of the first LogMessage
  131. // instance is created.
  132. static uint32 LogStartTime();
  133. // Returns the wall clock equivalent of |LogStartTime|, in seconds from the
  134. // epoch.
  135. static uint32 WallClockStartTime();
  136. // These are attributes which apply to all logging channels
  137. // LogContext: Display the file and line number of the message
  138. static void LogContext(int min_sev);
  139. // LogThreads: Display the thread identifier of the current thread
  140. static void LogThreads(bool on = true);
  141. // LogTimestamps: Display the elapsed time of the program
  142. static void LogTimestamps(bool on = true);
  143. // These are the available logging channels
  144. // Debug: Debug console on Windows, otherwise stderr
  145. static void LogToDebug(int min_sev);
  146. static int GetLogToDebug() { return dbg_sev_; }
  147. // Stream: Any non-blocking stream interface. LogMessage takes ownership of
  148. // the stream. Multiple streams may be specified by using AddLogToStream.
  149. // LogToStream is retained for backwards compatibility; when invoked, it
  150. // will discard any previously set streams and install the specified stream.
  151. // GetLogToStream gets the severity for the specified stream, of if none
  152. // is specified, the minimum stream severity.
  153. // RemoveLogToStream removes the specified stream, without destroying it.
  154. static void LogToStream(StreamInterface* stream, int min_sev);
  155. static int GetLogToStream(StreamInterface* stream = NULL);
  156. static void AddLogToStream(StreamInterface* stream, int min_sev);
  157. static void RemoveLogToStream(StreamInterface* stream);
  158. // Testing against MinLogSeverity allows code to avoid potentially expensive
  159. // logging operations by pre-checking the logging level.
  160. static int GetMinLogSeverity() { return min_sev_; }
  161. static void SetDiagnosticMode(bool f) { is_diagnostic_mode_ = f; }
  162. static bool IsDiagnosticMode() { return is_diagnostic_mode_; }
  163. // Parses the provided parameter stream to configure the options above.
  164. // Useful for configuring logging from the command line. If file logging
  165. // is enabled, it is output to the specified filename.
  166. static void ConfigureLogging(const char* params, const char* filename);
  167. // Convert the string to a LS_ value; also accept numeric values.
  168. static int ParseLogSeverity(const std::string& value);
  169. private:
  170. typedef std::list<std::pair<StreamInterface*, int> > StreamList;
  171. // Updates min_sev_ appropriately when debug sinks change.
  172. static void UpdateMinLogSeverity();
  173. // These assist in formatting some parts of the debug output.
  174. static const char* Describe(LoggingSeverity sev);
  175. static const char* DescribeFile(const char* file);
  176. // These write out the actual log messages.
  177. static void OutputToDebug(const std::string& msg, LoggingSeverity severity_);
  178. static void OutputToStream(StreamInterface* stream, const std::string& msg);
  179. // The ostream that buffers the formatted message before output
  180. std::ostringstream print_stream_;
  181. // The severity level of this message
  182. LoggingSeverity severity_;
  183. // String data generated in the constructor, that should be appended to
  184. // the message before output.
  185. std::string extra_;
  186. // If time it takes to write to stream is more than this, log one
  187. // additional warning about it.
  188. uint32 warn_slow_logs_delay_;
  189. // Global lock for the logging subsystem
  190. static CriticalSection crit_;
  191. // dbg_sev_ is the thresholds for those output targets
  192. // min_sev_ is the minimum (most verbose) of those levels, and is used
  193. // as a short-circuit in the logging macros to identify messages that won't
  194. // be logged.
  195. // ctx_sev_ is the minimum level at which file context is displayed
  196. static int min_sev_, dbg_sev_, ctx_sev_;
  197. // The output streams and their associated severities
  198. static StreamList streams_;
  199. // Flags for formatting options
  200. static bool thread_, timestamp_;
  201. // are we in diagnostic mode (as defined by the app)?
  202. static bool is_diagnostic_mode_;
  203. DISALLOW_EVIL_CONSTRUCTORS(LogMessage);
  204. };
  205. //////////////////////////////////////////////////////////////////////
  206. // Logging Helpers
  207. //////////////////////////////////////////////////////////////////////
  208. class LogMultilineState {
  209. public:
  210. size_t unprintable_count_[2];
  211. LogMultilineState() {
  212. unprintable_count_[0] = unprintable_count_[1] = 0;
  213. }
  214. };
  215. // When possible, pass optional state variable to track various data across
  216. // multiple calls to LogMultiline. Otherwise, pass NULL.
  217. void LogMultiline(LoggingSeverity level, const char* label, bool input,
  218. const void* data, size_t len, bool hex_mode,
  219. LogMultilineState* state);
  220. //////////////////////////////////////////////////////////////////////
  221. // Macros which automatically disable logging when LOGGING == 0
  222. //////////////////////////////////////////////////////////////////////
  223. // If LOGGING is not explicitly defined, default to enabled in debug mode
  224. #if !defined(LOGGING)
  225. #if defined(_DEBUG) && !defined(NDEBUG)
  226. #define LOGGING 1
  227. #else
  228. #define LOGGING 0
  229. #endif
  230. #endif // !defined(LOGGING)
  231. #ifndef LOG
  232. #if LOGGING
  233. // The following non-obvious technique for implementation of a
  234. // conditional log stream was stolen from google3/base/logging.h.
  235. // This class is used to explicitly ignore values in the conditional
  236. // logging macros. This avoids compiler warnings like "value computed
  237. // is not used" and "statement has no effect".
  238. class LogMessageVoidify {
  239. public:
  240. LogMessageVoidify() { }
  241. // This has to be an operator with a precedence lower than << but
  242. // higher than ?:
  243. void operator&(std::ostream&) { }
  244. };
  245. #define LOG_SEVERITY_PRECONDITION(sev) \
  246. !(talk_base::LogMessage::Loggable(sev)) \
  247. ? (void) 0 \
  248. : talk_base::LogMessageVoidify() &
  249. #define LOG(sev) \
  250. LOG_SEVERITY_PRECONDITION(talk_base::sev) \
  251. talk_base::LogMessage(__FILE__, __LINE__, talk_base::sev).stream()
  252. // The _V version is for when a variable is passed in. It doesn't do the
  253. // namespace concatination.
  254. #define LOG_V(sev) \
  255. LOG_SEVERITY_PRECONDITION(sev) \
  256. talk_base::LogMessage(__FILE__, __LINE__, sev).stream()
  257. // The _F version prefixes the message with the current function name.
  258. #if (defined(__GNUC__) && defined(_DEBUG)) || defined(WANT_PRETTY_LOG_F)
  259. #define LOG_F(sev) LOG(sev) << __PRETTY_FUNCTION__ << ": "
  260. #else
  261. #define LOG_F(sev) LOG(sev) << __FUNCTION__ << ": "
  262. #endif
  263. #define LOG_CHECK_LEVEL(sev) \
  264. talk_base::LogCheckLevel(talk_base::sev)
  265. #define LOG_CHECK_LEVEL_V(sev) \
  266. talk_base::LogCheckLevel(sev)
  267. inline bool LogCheckLevel(LoggingSeverity sev) {
  268. return (LogMessage::GetMinLogSeverity() <= sev);
  269. }
  270. #define LOG_E(sev, ctx, err, ...) \
  271. LOG_SEVERITY_PRECONDITION(talk_base::sev) \
  272. talk_base::LogMessage(__FILE__, __LINE__, talk_base::sev, \
  273. talk_base::ERRCTX_ ## ctx, err , ##__VA_ARGS__) \
  274. .stream()
  275. #else // !LOGGING
  276. // Hopefully, the compiler will optimize away some of this code.
  277. // Note: syntax of "1 ? (void)0 : LogMessage" was causing errors in g++,
  278. // converted to "while (false)"
  279. #define LOG(sev) \
  280. while (false)talk_base:: LogMessage(NULL, 0, talk_base::sev).stream()
  281. #define LOG_V(sev) \
  282. while (false) talk_base::LogMessage(NULL, 0, sev).stream()
  283. #define LOG_F(sev) LOG(sev) << __FUNCTION__ << ": "
  284. #define LOG_CHECK_LEVEL(sev) \
  285. false
  286. #define LOG_CHECK_LEVEL_V(sev) \
  287. false
  288. #define LOG_E(sev, ctx, err, ...) \
  289. while (false) talk_base::LogMessage(__FILE__, __LINE__, talk_base::sev, \
  290. talk_base::ERRCTX_ ## ctx, err , ##__VA_ARGS__) \
  291. .stream()
  292. #endif // !LOGGING
  293. #define LOG_ERRNO_EX(sev, err) \
  294. LOG_E(sev, ERRNO, err)
  295. #define LOG_ERRNO(sev) \
  296. LOG_ERRNO_EX(sev, errno)
  297. #ifdef WIN32
  298. #define LOG_GLE_EX(sev, err) \
  299. LOG_E(sev, HRESULT, err)
  300. #define LOG_GLE(sev) \
  301. LOG_GLE_EX(sev, GetLastError())
  302. #define LOG_GLEM(sev, mod) \
  303. LOG_E(sev, HRESULT, GetLastError(), mod)
  304. #define LOG_ERR_EX(sev, err) \
  305. LOG_GLE_EX(sev, err)
  306. #define LOG_ERR(sev) \
  307. LOG_GLE(sev)
  308. #define LAST_SYSTEM_ERROR \
  309. (::GetLastError())
  310. #elif POSIX
  311. #define LOG_ERR_EX(sev, err) \
  312. LOG_ERRNO_EX(sev, err)
  313. #define LOG_ERR(sev) \
  314. LOG_ERRNO(sev)
  315. #define LAST_SYSTEM_ERROR \
  316. (errno)
  317. #endif // WIN32
  318. #define PLOG(sev, err) \
  319. LOG_ERR_EX(sev, err)
  320. // TODO(?): Add an "assert" wrapper that logs in the same manner.
  321. #endif // LOG
  322. } // namespace talk_base
  323. #endif // TALK_BASE_LOGGING_H_