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.

555 lines
16 KiB

​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
  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. #if defined(WEBRTC_WIN)
  11. #include <windows.h>
  12. #if _MSC_VER < 1900
  13. #define snprintf _snprintf
  14. #endif
  15. #undef ERROR // wingdi.h
  16. #endif
  17. #if defined(WEBRTC_MAC) && !defined(WEBRTC_IOS)
  18. #include <CoreServices/CoreServices.h>
  19. #elif defined(WEBRTC_ANDROID)
  20. #include <android/log.h>
  21. // Android has a 1024 limit on log inputs. We use 60 chars as an
  22. // approx for the header/tag portion.
  23. // See android/system/core/liblog/logd_write.c
  24. static const int kMaxLogLineSize = 1024 - 60;
  25. #endif // WEBRTC_MAC && !defined(WEBRTC_IOS) || WEBRTC_ANDROID
  26. #include <stdio.h>
  27. #include <string.h>
  28. #include <time.h>
  29. #include <algorithm>
  30. #include <cstdarg>
  31. #include <vector>
  32. #include "absl/base/attributes.h"
  33. #include "rtc_base/checks.h"
  34. #include "rtc_base/critical_section.h"
  35. #include "rtc_base/logging.h"
  36. #include "rtc_base/platform_thread_types.h"
  37. #include "rtc_base/string_encode.h"
  38. #include "rtc_base/string_utils.h"
  39. #include "rtc_base/strings/string_builder.h"
  40. #include "rtc_base/thread_annotations.h"
  41. #include "rtc_base/time_utils.h"
  42. namespace rtc {
  43. namespace {
  44. // By default, release builds don't log, debug builds at info level
  45. #if !defined(NDEBUG)
  46. static LoggingSeverity g_min_sev = LS_INFO;
  47. static LoggingSeverity g_dbg_sev = LS_INFO;
  48. #else
  49. static LoggingSeverity g_min_sev = LS_NONE;
  50. static LoggingSeverity g_dbg_sev = LS_NONE;
  51. #endif
  52. // Return the filename portion of the string (that following the last slash).
  53. const char* FilenameFromPath(const char* file) {
  54. const char* end1 = ::strrchr(file, '/');
  55. const char* end2 = ::strrchr(file, '\\');
  56. if (!end1 && !end2)
  57. return file;
  58. else
  59. return (end1 > end2) ? end1 + 1 : end2 + 1;
  60. }
  61. // Global lock for log subsystem, only needed to serialize access to streams_.
  62. ABSL_CONST_INIT GlobalLock g_log_crit;
  63. } // namespace
  64. // Inefficient default implementation, override is recommended.
  65. void LogSink::OnLogMessage(const std::string& msg,
  66. LoggingSeverity severity,
  67. const char* tag) {
  68. OnLogMessage(tag + (": " + msg), severity);
  69. }
  70. void LogSink::OnLogMessage(const std::string& msg,
  71. LoggingSeverity /* severity */) {
  72. OnLogMessage(msg);
  73. }
  74. /////////////////////////////////////////////////////////////////////////////
  75. // LogMessage
  76. /////////////////////////////////////////////////////////////////////////////
  77. bool LogMessage::log_to_stderr_ = true;
  78. // The list of logging streams currently configured.
  79. // Note: we explicitly do not clean this up, because of the uncertain ordering
  80. // of destructors at program exit. Let the person who sets the stream trigger
  81. // cleanup by setting to null, or let it leak (safe at program exit).
  82. ABSL_CONST_INIT LogSink* LogMessage::streams_ RTC_GUARDED_BY(g_log_crit) =
  83. nullptr;
  84. // Boolean options default to false (0)
  85. bool LogMessage::thread_, LogMessage::timestamp_;
  86. LogMessage::LogMessage(const char* file, int line, LoggingSeverity sev)
  87. : LogMessage(file, line, sev, ERRCTX_NONE, 0) {}
  88. LogMessage::LogMessage(const char* file,
  89. int line,
  90. LoggingSeverity sev,
  91. LogErrorContext err_ctx,
  92. int err)
  93. : severity_(sev) {
  94. if (timestamp_) {
  95. // Use SystemTimeMillis so that even if tests use fake clocks, the timestamp
  96. // in log messages represents the real system time.
  97. int64_t time = TimeDiff(SystemTimeMillis(), LogStartTime());
  98. // Also ensure WallClockStartTime is initialized, so that it matches
  99. // LogStartTime.
  100. WallClockStartTime();
  101. print_stream_ << "[" << rtc::LeftPad('0', 3, rtc::ToString(time / 1000))
  102. << ":" << rtc::LeftPad('0', 3, rtc::ToString(time % 1000))
  103. << "] ";
  104. }
  105. if (thread_) {
  106. PlatformThreadId id = CurrentThreadId();
  107. print_stream_ << "[" << id << "] ";
  108. }
  109. if (file != nullptr) {
  110. #if defined(WEBRTC_ANDROID)
  111. tag_ = FilenameFromPath(file);
  112. print_stream_ << "(line " << line << "): ";
  113. #else
  114. print_stream_ << "(" << FilenameFromPath(file) << ":" << line << "): ";
  115. #endif
  116. }
  117. if (err_ctx != ERRCTX_NONE) {
  118. char tmp_buf[1024];
  119. SimpleStringBuilder tmp(tmp_buf);
  120. tmp.AppendFormat("[0x%08X]", err);
  121. switch (err_ctx) {
  122. case ERRCTX_ERRNO:
  123. tmp << " " << strerror(err);
  124. break;
  125. #ifdef WEBRTC_WIN
  126. case ERRCTX_HRESULT: {
  127. char msgbuf[256];
  128. DWORD flags =
  129. FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS;
  130. if (DWORD len = FormatMessageA(
  131. flags, nullptr, err, MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT),
  132. msgbuf, sizeof(msgbuf) / sizeof(msgbuf[0]), nullptr)) {
  133. while ((len > 0) &&
  134. isspace(static_cast<unsigned char>(msgbuf[len - 1]))) {
  135. msgbuf[--len] = 0;
  136. }
  137. tmp << " " << msgbuf;
  138. }
  139. break;
  140. }
  141. #endif // WEBRTC_WIN
  142. default:
  143. break;
  144. }
  145. extra_ = tmp.str();
  146. }
  147. }
  148. #if defined(WEBRTC_ANDROID)
  149. LogMessage::LogMessage(const char* file,
  150. int line,
  151. LoggingSeverity sev,
  152. const char* tag)
  153. : LogMessage(file, line, sev, ERRCTX_NONE, 0 /* err */) {
  154. tag_ = tag;
  155. print_stream_ << tag << ": ";
  156. }
  157. #endif
  158. // DEPRECATED. Currently only used by downstream projects that use
  159. // implementation details of logging.h. Work is ongoing to remove those
  160. // dependencies.
  161. LogMessage::LogMessage(const char* file,
  162. int line,
  163. LoggingSeverity sev,
  164. const std::string& tag)
  165. : LogMessage(file, line, sev) {
  166. print_stream_ << tag << ": ";
  167. }
  168. LogMessage::~LogMessage() {
  169. FinishPrintStream();
  170. const std::string str = print_stream_.Release();
  171. if (severity_ >= g_dbg_sev) {
  172. #if defined(WEBRTC_ANDROID)
  173. OutputToDebug(str, severity_, tag_);
  174. #else
  175. OutputToDebug(str, severity_);
  176. #endif
  177. }
  178. GlobalLockScope cs(&g_log_crit);
  179. for (LogSink* entry = streams_; entry != nullptr; entry = entry->next_) {
  180. if (severity_ >= entry->min_severity_) {
  181. #if defined(WEBRTC_ANDROID)
  182. entry->OnLogMessage(str, severity_, tag_);
  183. #else
  184. entry->OnLogMessage(str, severity_);
  185. #endif
  186. }
  187. }
  188. }
  189. void LogMessage::AddTag(const char* tag) {
  190. #ifdef WEBRTC_ANDROID
  191. tag_ = tag;
  192. #endif
  193. }
  194. rtc::StringBuilder& LogMessage::stream() {
  195. return print_stream_;
  196. }
  197. int LogMessage::GetMinLogSeverity() {
  198. return g_min_sev;
  199. }
  200. LoggingSeverity LogMessage::GetLogToDebug() {
  201. return g_dbg_sev;
  202. }
  203. int64_t LogMessage::LogStartTime() {
  204. static const int64_t g_start = SystemTimeMillis();
  205. return g_start;
  206. }
  207. uint32_t LogMessage::WallClockStartTime() {
  208. static const uint32_t g_start_wallclock = time(nullptr);
  209. return g_start_wallclock;
  210. }
  211. void LogMessage::LogThreads(bool on) {
  212. thread_ = on;
  213. }
  214. void LogMessage::LogTimestamps(bool on) {
  215. timestamp_ = on;
  216. }
  217. void LogMessage::LogToDebug(LoggingSeverity min_sev) {
  218. g_dbg_sev = min_sev;
  219. GlobalLockScope cs(&g_log_crit);
  220. UpdateMinLogSeverity();
  221. }
  222. void LogMessage::SetLogToStderr(bool log_to_stderr) {
  223. log_to_stderr_ = log_to_stderr;
  224. }
  225. int LogMessage::GetLogToStream(LogSink* stream) {
  226. GlobalLockScope cs(&g_log_crit);
  227. LoggingSeverity sev = LS_NONE;
  228. for (LogSink* entry = streams_; entry != nullptr; entry = entry->next_) {
  229. if (stream == nullptr || stream == entry) {
  230. sev = std::min(sev, entry->min_severity_);
  231. }
  232. }
  233. return sev;
  234. }
  235. void LogMessage::AddLogToStream(LogSink* stream, LoggingSeverity min_sev) {
  236. GlobalLockScope cs(&g_log_crit);
  237. stream->min_severity_ = min_sev;
  238. stream->next_ = streams_;
  239. streams_ = stream;
  240. UpdateMinLogSeverity();
  241. }
  242. void LogMessage::RemoveLogToStream(LogSink* stream) {
  243. GlobalLockScope cs(&g_log_crit);
  244. for (LogSink** entry = &streams_; *entry != nullptr;
  245. entry = &(*entry)->next_) {
  246. if (*entry == stream) {
  247. *entry = (*entry)->next_;
  248. break;
  249. }
  250. }
  251. UpdateMinLogSeverity();
  252. }
  253. void LogMessage::ConfigureLogging(const char* params) {
  254. LoggingSeverity current_level = LS_VERBOSE;
  255. LoggingSeverity debug_level = GetLogToDebug();
  256. std::vector<std::string> tokens;
  257. tokenize(params, ' ', &tokens);
  258. for (const std::string& token : tokens) {
  259. if (token.empty())
  260. continue;
  261. // Logging features
  262. if (token == "tstamp") {
  263. LogTimestamps();
  264. } else if (token == "thread") {
  265. LogThreads();
  266. // Logging levels
  267. } else if (token == "verbose") {
  268. current_level = LS_VERBOSE;
  269. } else if (token == "info") {
  270. current_level = LS_INFO;
  271. } else if (token == "warning") {
  272. current_level = LS_WARNING;
  273. } else if (token == "error") {
  274. current_level = LS_ERROR;
  275. } else if (token == "none") {
  276. current_level = LS_NONE;
  277. // Logging targets
  278. } else if (token == "debug") {
  279. debug_level = current_level;
  280. }
  281. }
  282. #if defined(WEBRTC_WIN) && !defined(WINUWP)
  283. if ((LS_NONE != debug_level) && !::IsDebuggerPresent()) {
  284. // First, attempt to attach to our parent's console... so if you invoke
  285. // from the command line, we'll see the output there. Otherwise, create
  286. // our own console window.
  287. // Note: These methods fail if a console already exists, which is fine.
  288. if (!AttachConsole(ATTACH_PARENT_PROCESS))
  289. ::AllocConsole();
  290. }
  291. #endif // defined(WEBRTC_WIN) && !defined(WINUWP)
  292. LogToDebug(debug_level);
  293. }
  294. void LogMessage::UpdateMinLogSeverity()
  295. RTC_EXCLUSIVE_LOCKS_REQUIRED(g_log_crit) {
  296. LoggingSeverity min_sev = g_dbg_sev;
  297. for (LogSink* entry = streams_; entry != nullptr; entry = entry->next_) {
  298. min_sev = std::min(min_sev, entry->min_severity_);
  299. }
  300. g_min_sev = min_sev;
  301. }
  302. #if defined(WEBRTC_ANDROID)
  303. void LogMessage::OutputToDebug(const std::string& str,
  304. LoggingSeverity severity,
  305. const char* tag) {
  306. #else
  307. void LogMessage::OutputToDebug(const std::string& str,
  308. LoggingSeverity severity) {
  309. #endif
  310. bool log_to_stderr = log_to_stderr_;
  311. #if defined(WEBRTC_MAC) && !defined(WEBRTC_IOS) && defined(NDEBUG)
  312. // On the Mac, all stderr output goes to the Console log and causes clutter.
  313. // So in opt builds, don't log to stderr unless the user specifically sets
  314. // a preference to do so.
  315. CFStringRef key = CFStringCreateWithCString(
  316. kCFAllocatorDefault, "logToStdErr", kCFStringEncodingUTF8);
  317. CFStringRef domain = CFBundleGetIdentifier(CFBundleGetMainBundle());
  318. if (key != nullptr && domain != nullptr) {
  319. Boolean exists_and_is_valid;
  320. Boolean should_log =
  321. CFPreferencesGetAppBooleanValue(key, domain, &exists_and_is_valid);
  322. // If the key doesn't exist or is invalid or is false, we will not log to
  323. // stderr.
  324. log_to_stderr = exists_and_is_valid && should_log;
  325. }
  326. if (key != nullptr) {
  327. CFRelease(key);
  328. }
  329. #endif // defined(WEBRTC_MAC) && !defined(WEBRTC_IOS) && defined(NDEBUG)
  330. #if defined(WEBRTC_WIN)
  331. // Always log to the debugger.
  332. // Perhaps stderr should be controlled by a preference, as on Mac?
  333. OutputDebugStringA(str.c_str());
  334. if (log_to_stderr) {
  335. // This handles dynamically allocated consoles, too.
  336. if (HANDLE error_handle = ::GetStdHandle(STD_ERROR_HANDLE)) {
  337. log_to_stderr = false;
  338. DWORD written = 0;
  339. ::WriteFile(error_handle, str.data(), static_cast<DWORD>(str.size()),
  340. &written, 0);
  341. }
  342. }
  343. #endif // WEBRTC_WIN
  344. #if defined(WEBRTC_ANDROID)
  345. // Android's logging facility uses severity to log messages but we
  346. // need to map libjingle's severity levels to Android ones first.
  347. // Also write to stderr which maybe available to executable started
  348. // from the shell.
  349. int prio;
  350. switch (severity) {
  351. case LS_VERBOSE:
  352. prio = ANDROID_LOG_VERBOSE;
  353. break;
  354. case LS_INFO:
  355. prio = ANDROID_LOG_INFO;
  356. break;
  357. case LS_WARNING:
  358. prio = ANDROID_LOG_WARN;
  359. break;
  360. case LS_ERROR:
  361. prio = ANDROID_LOG_ERROR;
  362. break;
  363. default:
  364. prio = ANDROID_LOG_UNKNOWN;
  365. }
  366. int size = str.size();
  367. int line = 0;
  368. int idx = 0;
  369. const int max_lines = size / kMaxLogLineSize + 1;
  370. if (max_lines == 1) {
  371. __android_log_print(prio, tag, "%.*s", size, str.c_str());
  372. } else {
  373. while (size > 0) {
  374. const int len = std::min(size, kMaxLogLineSize);
  375. // Use the size of the string in the format (str may have \0 in the
  376. // middle).
  377. __android_log_print(prio, tag, "[%d/%d] %.*s", line + 1, max_lines, len,
  378. str.c_str() + idx);
  379. idx += len;
  380. size -= len;
  381. ++line;
  382. }
  383. }
  384. #endif // WEBRTC_ANDROID
  385. if (log_to_stderr) {
  386. fprintf(stderr, "%s", str.c_str());
  387. fflush(stderr);
  388. }
  389. }
  390. // static
  391. bool LogMessage::IsNoop(LoggingSeverity severity) {
  392. if (severity >= g_dbg_sev || severity >= g_min_sev)
  393. return false;
  394. // TODO(tommi): We're grabbing this lock for every LogMessage instance that
  395. // is going to be logged. This introduces unnecessary synchronization for
  396. // a feature that's mostly used for testing.
  397. GlobalLockScope cs(&g_log_crit);
  398. return streams_ == nullptr;
  399. }
  400. void LogMessage::FinishPrintStream() {
  401. if (!extra_.empty())
  402. print_stream_ << " : " << extra_;
  403. print_stream_ << "\n";
  404. }
  405. namespace webrtc_logging_impl {
  406. void Log(const LogArgType* fmt, ...) {
  407. va_list args;
  408. va_start(args, fmt);
  409. LogMetadataErr meta;
  410. const char* tag = nullptr;
  411. switch (*fmt) {
  412. case LogArgType::kLogMetadata: {
  413. meta = {va_arg(args, LogMetadata), ERRCTX_NONE, 0};
  414. break;
  415. }
  416. case LogArgType::kLogMetadataErr: {
  417. meta = va_arg(args, LogMetadataErr);
  418. break;
  419. }
  420. #ifdef WEBRTC_ANDROID
  421. case LogArgType::kLogMetadataTag: {
  422. const LogMetadataTag tag_meta = va_arg(args, LogMetadataTag);
  423. meta = {{nullptr, 0, tag_meta.severity}, ERRCTX_NONE, 0};
  424. tag = tag_meta.tag;
  425. break;
  426. }
  427. #endif
  428. default: {
  429. RTC_NOTREACHED();
  430. va_end(args);
  431. return;
  432. }
  433. }
  434. if (LogMessage::IsNoop(meta.meta.Severity())) {
  435. va_end(args);
  436. return;
  437. }
  438. LogMessage log_message(meta.meta.File(), meta.meta.Line(),
  439. meta.meta.Severity(), meta.err_ctx, meta.err);
  440. if (tag) {
  441. log_message.AddTag(tag);
  442. }
  443. for (++fmt; *fmt != LogArgType::kEnd; ++fmt) {
  444. switch (*fmt) {
  445. case LogArgType::kInt:
  446. log_message.stream() << va_arg(args, int);
  447. break;
  448. case LogArgType::kLong:
  449. log_message.stream() << va_arg(args, long);
  450. break;
  451. case LogArgType::kLongLong:
  452. log_message.stream() << va_arg(args, long long);
  453. break;
  454. case LogArgType::kUInt:
  455. log_message.stream() << va_arg(args, unsigned);
  456. break;
  457. case LogArgType::kULong:
  458. log_message.stream() << va_arg(args, unsigned long);
  459. break;
  460. case LogArgType::kULongLong:
  461. log_message.stream() << va_arg(args, unsigned long long);
  462. break;
  463. case LogArgType::kDouble:
  464. log_message.stream() << va_arg(args, double);
  465. break;
  466. case LogArgType::kLongDouble:
  467. log_message.stream() << va_arg(args, long double);
  468. break;
  469. case LogArgType::kCharP: {
  470. const char* s = va_arg(args, const char*);
  471. log_message.stream() << (s ? s : "(null)");
  472. break;
  473. }
  474. case LogArgType::kStdString:
  475. log_message.stream() << *va_arg(args, const std::string*);
  476. break;
  477. case LogArgType::kStringView:
  478. log_message.stream() << *va_arg(args, const absl::string_view*);
  479. break;
  480. case LogArgType::kVoidP:
  481. log_message.stream() << rtc::ToHex(
  482. reinterpret_cast<uintptr_t>(va_arg(args, const void*)));
  483. break;
  484. default:
  485. RTC_NOTREACHED();
  486. va_end(args);
  487. return;
  488. }
  489. }
  490. va_end(args);
  491. }
  492. } // namespace webrtc_logging_impl
  493. } // namespace rtc