blob: 1ac1373fb11b9deb640b485980cd05a44dbf09df [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#if defined(WEBRTC_WIN)
Tommi23edcff2015-05-25 10:45:43 +020012#if !defined(WIN32_LEAN_AND_MEAN)
henrike@webrtc.orgf0488722014-05-13 18:00:26 +000013#define WIN32_LEAN_AND_MEAN
Tommi23edcff2015-05-25 10:45:43 +020014#endif
henrike@webrtc.orgf0488722014-05-13 18:00:26 +000015#include <windows.h>
16#define snprintf _snprintf
17#undef ERROR // wingdi.h
18#endif
19
20#if defined(WEBRTC_MAC) && !defined(WEBRTC_IOS)
21#include <CoreServices/CoreServices.h>
22#elif defined(WEBRTC_ANDROID)
23#include <android/log.h>
24static const char kLibjingle[] = "libjingle";
25// Android has a 1024 limit on log inputs. We use 60 chars as an
26// approx for the header/tag portion.
27// See android/system/core/liblog/logd_write.c
28static const int kMaxLogLineSize = 1024 - 60;
29#endif // WEBRTC_MAC && !defined(WEBRTC_IOS) || WEBRTC_ANDROID
30
31#include <time.h>
henrike@webrtc.orgf0488722014-05-13 18:00:26 +000032#include <limits.h>
andresp@webrtc.orgff689be2015-02-12 11:54:26 +000033
34#include <algorithm>
35#include <iomanip>
36#include <ostream>
henrike@webrtc.orgf0488722014-05-13 18:00:26 +000037#include <vector>
38
39#include "webrtc/base/logging.h"
Tommi0eefb4d2015-05-23 09:54:07 +020040#include "webrtc/base/scoped_ptr.h"
henrike@webrtc.orgf0488722014-05-13 18:00:26 +000041#include "webrtc/base/stringencode.h"
42#include "webrtc/base/stringutils.h"
43#include "webrtc/base/timeutils.h"
44
45namespace rtc {
46
47/////////////////////////////////////////////////////////////////////////////
48// Constant Labels
49/////////////////////////////////////////////////////////////////////////////
50
51const char * FindLabel(int value, const ConstantLabel entries[]) {
52 for (int i = 0; entries[i].label; ++i) {
53 if (value == entries[i].value) {
54 return entries[i].label;
55 }
56 }
57 return 0;
58}
59
60std::string ErrorName(int err, const ConstantLabel * err_table) {
61 if (err == 0)
62 return "No error";
63
64 if (err_table != 0) {
65 if (const char * value = FindLabel(err, err_table))
66 return value;
67 }
68
69 char buffer[16];
70 snprintf(buffer, sizeof(buffer), "0x%08x", err);
71 return buffer;
72}
73
74/////////////////////////////////////////////////////////////////////////////
75// LogMessage
76/////////////////////////////////////////////////////////////////////////////
77
Tommi0eefb4d2015-05-23 09:54:07 +020078// By default, release builds don't log, debug builds at info level
henrike@webrtc.orgf0488722014-05-13 18:00:26 +000079#if _DEBUG
Tommi0eefb4d2015-05-23 09:54:07 +020080LoggingSeverity LogMessage::min_sev_ = LS_INFO;
81LoggingSeverity LogMessage::dbg_sev_ = LS_INFO;
henrike@webrtc.orgf0488722014-05-13 18:00:26 +000082#else // !_DEBUG
Tommi0eefb4d2015-05-23 09:54:07 +020083LoggingSeverity LogMessage::min_sev_ = LS_NONE;
84LoggingSeverity LogMessage::dbg_sev_ = LS_NONE;
henrike@webrtc.orgf0488722014-05-13 18:00:26 +000085#endif // !_DEBUG
86
87// Global lock for log subsystem, only needed to serialize access to streams_.
88CriticalSection LogMessage::crit_;
89
henrike@webrtc.orgf0488722014-05-13 18:00:26 +000090// The list of logging streams currently configured.
91// Note: we explicitly do not clean this up, because of the uncertain ordering
92// of destructors at program exit. Let the person who sets the stream trigger
93// cleanup by setting to NULL, or let it leak (safe at program exit).
Tommi00aac5a2015-05-25 11:25:59 +020094LogMessage::StreamList LogMessage::streams_ GUARDED_BY(LogMessage::crit_);
henrike@webrtc.orgf0488722014-05-13 18:00:26 +000095
96// Boolean options default to false (0)
97bool LogMessage::thread_, LogMessage::timestamp_;
98
henrike@webrtc.orgf0488722014-05-13 18:00:26 +000099LogMessage::LogMessage(const char* file, int line, LoggingSeverity sev,
100 LogErrorContext err_ctx, int err, const char* module)
101 : severity_(sev),
102 warn_slow_logs_delay_(WARN_SLOW_LOGS_DELAY) {
103 if (timestamp_) {
104 uint32 time = TimeSince(LogStartTime());
105 // Also ensure WallClockStartTime is initialized, so that it matches
106 // LogStartTime.
107 WallClockStartTime();
108 print_stream_ << "[" << std::setfill('0') << std::setw(3) << (time / 1000)
109 << ":" << std::setw(3) << (time % 1000) << std::setfill(' ')
110 << "] ";
111 }
112
113 if (thread_) {
114#if defined(WEBRTC_WIN)
115 DWORD id = GetCurrentThreadId();
116 print_stream_ << "[" << std::hex << id << std::dec << "] ";
Tommi0eefb4d2015-05-23 09:54:07 +0200117#endif // WEBRTC_WIN
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000118 }
119
120 if (err_ctx != ERRCTX_NONE) {
121 std::ostringstream tmp;
122 tmp << "[0x" << std::setfill('0') << std::hex << std::setw(8) << err << "]";
123 switch (err_ctx) {
124 case ERRCTX_ERRNO:
125 tmp << " " << strerror(err);
126 break;
127#if WEBRTC_WIN
128 case ERRCTX_HRESULT: {
129 char msgbuf[256];
130 DWORD flags = FORMAT_MESSAGE_FROM_SYSTEM;
131 HMODULE hmod = GetModuleHandleA(module);
132 if (hmod)
133 flags |= FORMAT_MESSAGE_FROM_HMODULE;
134 if (DWORD len = FormatMessageA(
135 flags, hmod, err,
136 MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT),
137 msgbuf, sizeof(msgbuf) / sizeof(msgbuf[0]), NULL)) {
138 while ((len > 0) &&
139 isspace(static_cast<unsigned char>(msgbuf[len-1]))) {
140 msgbuf[--len] = 0;
141 }
142 tmp << " " << msgbuf;
143 }
144 break;
145 }
Tommi0eefb4d2015-05-23 09:54:07 +0200146#endif // WEBRTC_WIN
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000147#if defined(WEBRTC_MAC) && !defined(WEBRTC_IOS)
148 case ERRCTX_OSSTATUS: {
149 tmp << " " << nonnull(GetMacOSStatusErrorString(err), "Unknown error");
150 if (const char* desc = GetMacOSStatusCommentString(err)) {
151 tmp << ": " << desc;
152 }
153 break;
154 }
155#endif // WEBRTC_MAC && !defined(WEBRTC_IOS)
156 default:
157 break;
158 }
159 extra_ = tmp.str();
160 }
161}
162
163LogMessage::~LogMessage() {
164 if (!extra_.empty())
165 print_stream_ << " : " << extra_;
166 print_stream_ << std::endl;
167
168 const std::string& str = print_stream_.str();
169 if (severity_ >= dbg_sev_) {
170 OutputToDebug(str, severity_);
171 }
172
173 uint32 before = Time();
174 // Must lock streams_ before accessing
175 CritScope cs(&crit_);
176 for (StreamList::iterator it = streams_.begin(); it != streams_.end(); ++it) {
177 if (severity_ >= it->second) {
Tommi0eefb4d2015-05-23 09:54:07 +0200178 it->first->OnLogMessage(str);
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000179 }
180 }
181 uint32 delay = TimeSince(before);
182 if (delay >= warn_slow_logs_delay_) {
183 LogMessage slow_log_warning =
184 rtc::LogMessage(__FILE__, __LINE__, LS_WARNING);
185 // If our warning is slow, we don't want to warn about it, because
186 // that would lead to inifinite recursion. So, give a really big
187 // number for the delay threshold.
188 slow_log_warning.warn_slow_logs_delay_ = UINT_MAX;
189 slow_log_warning.stream() << "Slow log: took " << delay << "ms to write "
190 << str.size() << " bytes.";
191 }
192}
193
194uint32 LogMessage::LogStartTime() {
195 static const uint32 g_start = Time();
196 return g_start;
197}
198
199uint32 LogMessage::WallClockStartTime() {
200 static const uint32 g_start_wallclock = time(NULL);
201 return g_start_wallclock;
202}
203
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000204void LogMessage::LogThreads(bool on) {
205 thread_ = on;
206}
207
208void LogMessage::LogTimestamps(bool on) {
209 timestamp_ = on;
210}
211
Tommi0eefb4d2015-05-23 09:54:07 +0200212void LogMessage::LogToDebug(LoggingSeverity min_sev) {
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000213 dbg_sev_ = min_sev;
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000214 CritScope cs(&crit_);
Tommi00aac5a2015-05-25 11:25:59 +0200215 UpdateMinLogSeverity();
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000216}
217
Tommi0eefb4d2015-05-23 09:54:07 +0200218int LogMessage::GetLogToStream(LogSink* stream) {
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000219 CritScope cs(&crit_);
Tommi0eefb4d2015-05-23 09:54:07 +0200220 LoggingSeverity sev = LS_NONE;
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000221 for (StreamList::iterator it = streams_.begin(); it != streams_.end(); ++it) {
222 if (!stream || stream == it->first) {
andresp@webrtc.orgff689be2015-02-12 11:54:26 +0000223 sev = std::min(sev, it->second);
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000224 }
225 }
226 return sev;
227}
228
Tommi0eefb4d2015-05-23 09:54:07 +0200229void LogMessage::AddLogToStream(LogSink* stream, LoggingSeverity min_sev) {
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000230 CritScope cs(&crit_);
231 streams_.push_back(std::make_pair(stream, min_sev));
232 UpdateMinLogSeverity();
233}
234
Tommi0eefb4d2015-05-23 09:54:07 +0200235void LogMessage::RemoveLogToStream(LogSink* stream) {
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000236 CritScope cs(&crit_);
237 for (StreamList::iterator it = streams_.begin(); it != streams_.end(); ++it) {
238 if (stream == it->first) {
239 streams_.erase(it);
240 break;
241 }
242 }
243 UpdateMinLogSeverity();
244}
245
Tommi0eefb4d2015-05-23 09:54:07 +0200246void LogMessage::ConfigureLogging(const char* params) {
247 LoggingSeverity current_level = LS_VERBOSE;
248 LoggingSeverity debug_level = GetLogToDebug();
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000249
250 std::vector<std::string> tokens;
251 tokenize(params, ' ', &tokens);
252
Tommi0eefb4d2015-05-23 09:54:07 +0200253 for (const std::string& token : tokens) {
254 if (token.empty())
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000255 continue;
256
257 // Logging features
Tommi0eefb4d2015-05-23 09:54:07 +0200258 if (token == "tstamp") {
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000259 LogTimestamps();
Tommi0eefb4d2015-05-23 09:54:07 +0200260 } else if (token == "thread") {
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000261 LogThreads();
262
263 // Logging levels
Tommi0eefb4d2015-05-23 09:54:07 +0200264 } else if (token == "sensitive") {
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000265 current_level = LS_SENSITIVE;
Tommi0eefb4d2015-05-23 09:54:07 +0200266 } else if (token == "verbose") {
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000267 current_level = LS_VERBOSE;
Tommi0eefb4d2015-05-23 09:54:07 +0200268 } else if (token == "info") {
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000269 current_level = LS_INFO;
Tommi0eefb4d2015-05-23 09:54:07 +0200270 } else if (token == "warning") {
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000271 current_level = LS_WARNING;
Tommi0eefb4d2015-05-23 09:54:07 +0200272 } else if (token == "error") {
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000273 current_level = LS_ERROR;
Tommi0eefb4d2015-05-23 09:54:07 +0200274 } else if (token == "none") {
275 current_level = LS_NONE;
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000276
277 // Logging targets
Tommi0eefb4d2015-05-23 09:54:07 +0200278 } else if (token == "debug") {
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000279 debug_level = current_level;
280 }
281 }
282
283#if defined(WEBRTC_WIN)
Tommi0eefb4d2015-05-23 09:54:07 +0200284 if ((LS_NONE != debug_level) && !::IsDebuggerPresent()) {
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000285 // First, attempt to attach to our parent's console... so if you invoke
286 // from the command line, we'll see the output there. Otherwise, create
287 // our own console window.
288 // Note: These methods fail if a console already exists, which is fine.
289 bool success = false;
290 typedef BOOL (WINAPI* PFN_AttachConsole)(DWORD);
291 if (HINSTANCE kernel32 = ::LoadLibrary(L"kernel32.dll")) {
292 // AttachConsole is defined on WinXP+.
293 if (PFN_AttachConsole attach_console = reinterpret_cast<PFN_AttachConsole>
294 (::GetProcAddress(kernel32, "AttachConsole"))) {
295 success = (FALSE != attach_console(ATTACH_PARENT_PROCESS));
296 }
297 ::FreeLibrary(kernel32);
298 }
299 if (!success) {
300 ::AllocConsole();
301 }
302 }
Tommi0eefb4d2015-05-23 09:54:07 +0200303#endif // WEBRTC_WIN
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000304
305 LogToDebug(debug_level);
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000306}
307
Tommi00aac5a2015-05-25 11:25:59 +0200308void LogMessage::UpdateMinLogSeverity() EXCLUSIVE_LOCKS_REQUIRED(crit_) {
Tommi0eefb4d2015-05-23 09:54:07 +0200309 LoggingSeverity min_sev = dbg_sev_;
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000310 for (StreamList::iterator it = streams_.begin(); it != streams_.end(); ++it) {
andresp@webrtc.orgff689be2015-02-12 11:54:26 +0000311 min_sev = std::min(dbg_sev_, it->second);
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000312 }
313 min_sev_ = min_sev;
314}
315
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000316void LogMessage::OutputToDebug(const std::string& str,
317 LoggingSeverity severity) {
318 bool log_to_stderr = true;
319#if defined(WEBRTC_MAC) && !defined(WEBRTC_IOS) && (!defined(DEBUG) || defined(NDEBUG))
320 // On the Mac, all stderr output goes to the Console log and causes clutter.
321 // So in opt builds, don't log to stderr unless the user specifically sets
322 // a preference to do so.
323 CFStringRef key = CFStringCreateWithCString(kCFAllocatorDefault,
324 "logToStdErr",
325 kCFStringEncodingUTF8);
326 CFStringRef domain = CFBundleGetIdentifier(CFBundleGetMainBundle());
327 if (key != NULL && domain != NULL) {
328 Boolean exists_and_is_valid;
329 Boolean should_log =
330 CFPreferencesGetAppBooleanValue(key, domain, &exists_and_is_valid);
331 // If the key doesn't exist or is invalid or is false, we will not log to
332 // stderr.
333 log_to_stderr = exists_and_is_valid && should_log;
334 }
335 if (key != NULL) {
336 CFRelease(key);
337 }
338#endif
339#if defined(WEBRTC_WIN)
340 // Always log to the debugger.
341 // Perhaps stderr should be controlled by a preference, as on Mac?
342 OutputDebugStringA(str.c_str());
343 if (log_to_stderr) {
344 // This handles dynamically allocated consoles, too.
345 if (HANDLE error_handle = ::GetStdHandle(STD_ERROR_HANDLE)) {
346 log_to_stderr = false;
347 DWORD written = 0;
348 ::WriteFile(error_handle, str.data(), static_cast<DWORD>(str.size()),
349 &written, 0);
350 }
351 }
Tommi0eefb4d2015-05-23 09:54:07 +0200352#endif // WEBRTC_WIN
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000353#if defined(WEBRTC_ANDROID)
354 // Android's logging facility uses severity to log messages but we
355 // need to map libjingle's severity levels to Android ones first.
356 // Also write to stderr which maybe available to executable started
357 // from the shell.
358 int prio;
359 switch (severity) {
360 case LS_SENSITIVE:
361 __android_log_write(ANDROID_LOG_INFO, kLibjingle, "SENSITIVE");
362 if (log_to_stderr) {
363 fprintf(stderr, "SENSITIVE");
364 fflush(stderr);
365 }
366 return;
367 case LS_VERBOSE:
368 prio = ANDROID_LOG_VERBOSE;
369 break;
370 case LS_INFO:
371 prio = ANDROID_LOG_INFO;
372 break;
373 case LS_WARNING:
374 prio = ANDROID_LOG_WARN;
375 break;
376 case LS_ERROR:
377 prio = ANDROID_LOG_ERROR;
378 break;
379 default:
380 prio = ANDROID_LOG_UNKNOWN;
381 }
382
383 int size = str.size();
384 int line = 0;
385 int idx = 0;
386 const int max_lines = size / kMaxLogLineSize + 1;
387 if (max_lines == 1) {
388 __android_log_print(prio, kLibjingle, "%.*s", size, str.c_str());
389 } else {
390 while (size > 0) {
391 const int len = std::min(size, kMaxLogLineSize);
392 // Use the size of the string in the format (str may have \0 in the
393 // middle).
394 __android_log_print(prio, kLibjingle, "[%d/%d] %.*s",
395 line + 1, max_lines,
396 len, str.c_str() + idx);
397 idx += len;
398 size -= len;
399 ++line;
400 }
401 }
402#endif // WEBRTC_ANDROID
403 if (log_to_stderr) {
404 fprintf(stderr, "%s", str.c_str());
405 fflush(stderr);
406 }
407}
408
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000409//////////////////////////////////////////////////////////////////////
410// Logging Helpers
411//////////////////////////////////////////////////////////////////////
412
413void LogMultiline(LoggingSeverity level, const char* label, bool input,
414 const void* data, size_t len, bool hex_mode,
415 LogMultilineState* state) {
416 if (!LOG_CHECK_LEVEL_V(level))
417 return;
418
419 const char * direction = (input ? " << " : " >> ");
420
421 // NULL data means to flush our count of unprintable characters.
422 if (!data) {
423 if (state && state->unprintable_count_[input]) {
424 LOG_V(level) << label << direction << "## "
425 << state->unprintable_count_[input]
426 << " consecutive unprintable ##";
427 state->unprintable_count_[input] = 0;
428 }
429 return;
430 }
431
432 // The ctype classification functions want unsigned chars.
433 const unsigned char* udata = static_cast<const unsigned char*>(data);
434
435 if (hex_mode) {
436 const size_t LINE_SIZE = 24;
437 char hex_line[LINE_SIZE * 9 / 4 + 2], asc_line[LINE_SIZE + 1];
438 while (len > 0) {
439 memset(asc_line, ' ', sizeof(asc_line));
440 memset(hex_line, ' ', sizeof(hex_line));
andresp@webrtc.orgff689be2015-02-12 11:54:26 +0000441 size_t line_len = std::min(len, LINE_SIZE);
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000442 for (size_t i = 0; i < line_len; ++i) {
443 unsigned char ch = udata[i];
444 asc_line[i] = isprint(ch) ? ch : '.';
445 hex_line[i*2 + i/4] = hex_encode(ch >> 4);
446 hex_line[i*2 + i/4 + 1] = hex_encode(ch & 0xf);
447 }
448 asc_line[sizeof(asc_line)-1] = 0;
449 hex_line[sizeof(hex_line)-1] = 0;
450 LOG_V(level) << label << direction
451 << asc_line << " " << hex_line << " ";
452 udata += line_len;
453 len -= line_len;
454 }
455 return;
456 }
457
458 size_t consecutive_unprintable = state ? state->unprintable_count_[input] : 0;
459
460 const unsigned char* end = udata + len;
461 while (udata < end) {
462 const unsigned char* line = udata;
463 const unsigned char* end_of_line = strchrn<unsigned char>(udata,
464 end - udata,
465 '\n');
466 if (!end_of_line) {
467 udata = end_of_line = end;
468 } else {
469 udata = end_of_line + 1;
470 }
471
472 bool is_printable = true;
473
474 // If we are in unprintable mode, we need to see a line of at least
475 // kMinPrintableLine characters before we'll switch back.
476 const ptrdiff_t kMinPrintableLine = 4;
477 if (consecutive_unprintable && ((end_of_line - line) < kMinPrintableLine)) {
478 is_printable = false;
479 } else {
480 // Determine if the line contains only whitespace and printable
481 // characters.
482 bool is_entirely_whitespace = true;
483 for (const unsigned char* pos = line; pos < end_of_line; ++pos) {
484 if (isspace(*pos))
485 continue;
486 is_entirely_whitespace = false;
487 if (!isprint(*pos)) {
488 is_printable = false;
489 break;
490 }
491 }
492 // Treat an empty line following unprintable data as unprintable.
493 if (consecutive_unprintable && is_entirely_whitespace) {
494 is_printable = false;
495 }
496 }
497 if (!is_printable) {
498 consecutive_unprintable += (udata - line);
499 continue;
500 }
501 // Print out the current line, but prefix with a count of prior unprintable
502 // characters.
503 if (consecutive_unprintable) {
504 LOG_V(level) << label << direction << "## " << consecutive_unprintable
505 << " consecutive unprintable ##";
506 consecutive_unprintable = 0;
507 }
508 // Strip off trailing whitespace.
509 while ((end_of_line > line) && isspace(*(end_of_line-1))) {
510 --end_of_line;
511 }
512 // Filter out any private data
513 std::string substr(reinterpret_cast<const char*>(line), end_of_line - line);
514 std::string::size_type pos_private = substr.find("Email");
515 if (pos_private == std::string::npos) {
516 pos_private = substr.find("Passwd");
517 }
518 if (pos_private == std::string::npos) {
519 LOG_V(level) << label << direction << substr;
520 } else {
521 LOG_V(level) << label << direction << "## omitted for privacy ##";
522 }
523 }
524
525 if (state) {
526 state->unprintable_count_[input] = consecutive_unprintable;
527 }
528}
529
530//////////////////////////////////////////////////////////////////////
531
532} // namespace rtc