Bitcoin Core  24.1.0
P2P Digital Currency
logging.cpp
Go to the documentation of this file.
1 // Copyright (c) 2009-2010 Satoshi Nakamoto
2 // Copyright (c) 2009-2021 The Bitcoin Core developers
3 // Distributed under the MIT software license, see the accompanying
4 // file COPYING or http://www.opensource.org/licenses/mit-license.php.
5 
6 #include <fs.h>
7 #include <logging.h>
8 #include <util/string.h>
9 #include <util/threadnames.h>
10 #include <util/time.h>
11 
12 #include <algorithm>
13 #include <array>
14 #include <mutex>
15 #include <optional>
16 
17 const char * const DEFAULT_DEBUGLOGFILE = "debug.log";
19 
21 {
37  static BCLog::Logger* g_logger{new BCLog::Logger()};
38  return *g_logger;
39 }
40 
42 
43 static int FileWriteStr(const std::string &str, FILE *fp)
44 {
45  return fwrite(str.data(), 1, str.size(), fp);
46 }
47 
49 {
50  StdLockGuard scoped_lock(m_cs);
51 
52  assert(m_buffering);
53  assert(m_fileout == nullptr);
54 
55  if (m_print_to_file) {
56  assert(!m_file_path.empty());
57  m_fileout = fsbridge::fopen(m_file_path, "a");
58  if (!m_fileout) {
59  return false;
60  }
61 
62  setbuf(m_fileout, nullptr); // unbuffered
63 
64  // Add newlines to the logfile to distinguish this execution from the
65  // last one.
66  FileWriteStr("\n\n\n\n\n", m_fileout);
67  }
68 
69  // dump buffered messages from before we opened the log
70  m_buffering = false;
71  while (!m_msgs_before_open.empty()) {
72  const std::string& s = m_msgs_before_open.front();
73 
74  if (m_print_to_file) FileWriteStr(s, m_fileout);
75  if (m_print_to_console) fwrite(s.data(), 1, s.size(), stdout);
76  for (const auto& cb : m_print_callbacks) {
77  cb(s);
78  }
79 
80  m_msgs_before_open.pop_front();
81  }
82  if (m_print_to_console) fflush(stdout);
83 
84  return true;
85 }
86 
88 {
89  StdLockGuard scoped_lock(m_cs);
90  m_buffering = true;
91  if (m_fileout != nullptr) fclose(m_fileout);
92  m_fileout = nullptr;
93  m_print_callbacks.clear();
94 }
95 
97 {
98  m_categories |= flag;
99 }
100 
101 bool BCLog::Logger::EnableCategory(const std::string& str)
102 {
103  BCLog::LogFlags flag;
104  if (!GetLogCategory(flag, str)) return false;
105  EnableCategory(flag);
106  return true;
107 }
108 
110 {
111  m_categories &= ~flag;
112 }
113 
114 bool BCLog::Logger::DisableCategory(const std::string& str)
115 {
116  BCLog::LogFlags flag;
117  if (!GetLogCategory(flag, str)) return false;
118  DisableCategory(flag);
119  return true;
120 }
121 
123 {
124  return (m_categories.load(std::memory_order_relaxed) & category) != 0;
125 }
126 
128 {
129  // Log messages at Warning and Error level unconditionally, so that
130  // important troubleshooting information doesn't get lost.
131  if (level >= BCLog::Level::Warning) return true;
132 
133  if (!WillLogCategory(category)) return false;
134 
135  StdLockGuard scoped_lock(m_cs);
136  const auto it{m_category_log_levels.find(category)};
137  return level >= (it == m_category_log_levels.end() ? LogLevel() : it->second);
138 }
139 
141 {
142  return m_categories == BCLog::NONE;
143 }
144 
147  std::string category;
148 };
149 
151 {
152  {BCLog::NONE, "0"},
153  {BCLog::NONE, ""},
154  {BCLog::NET, "net"},
155  {BCLog::TOR, "tor"},
156  {BCLog::MEMPOOL, "mempool"},
157  {BCLog::HTTP, "http"},
158  {BCLog::BENCH, "bench"},
159  {BCLog::ZMQ, "zmq"},
160  {BCLog::WALLETDB, "walletdb"},
161  {BCLog::RPC, "rpc"},
162  {BCLog::ESTIMATEFEE, "estimatefee"},
163  {BCLog::ADDRMAN, "addrman"},
164  {BCLog::SELECTCOINS, "selectcoins"},
165  {BCLog::REINDEX, "reindex"},
166  {BCLog::CMPCTBLOCK, "cmpctblock"},
167  {BCLog::RAND, "rand"},
168  {BCLog::PRUNE, "prune"},
169  {BCLog::PROXY, "proxy"},
170  {BCLog::MEMPOOLREJ, "mempoolrej"},
171  {BCLog::LIBEVENT, "libevent"},
172  {BCLog::COINDB, "coindb"},
173  {BCLog::QT, "qt"},
174  {BCLog::LEVELDB, "leveldb"},
175  {BCLog::VALIDATION, "validation"},
176  {BCLog::I2P, "i2p"},
177  {BCLog::IPC, "ipc"},
178 #ifdef DEBUG_LOCKCONTENTION
179  {BCLog::LOCK, "lock"},
180 #endif
181  {BCLog::UTIL, "util"},
182  {BCLog::BLOCKSTORE, "blockstorage"},
183  {BCLog::ALL, "1"},
184  {BCLog::ALL, "all"},
185 };
186 
187 bool GetLogCategory(BCLog::LogFlags& flag, const std::string& str)
188 {
189  if (str.empty()) {
190  flag = BCLog::ALL;
191  return true;
192  }
193  for (const CLogCategoryDesc& category_desc : LogCategories) {
194  if (category_desc.category == str) {
195  flag = category_desc.flag;
196  return true;
197  }
198  }
199  return false;
200 }
201 
203 {
204  switch (level) {
205  case BCLog::Level::Trace:
206  return "trace";
207  case BCLog::Level::Debug:
208  return "debug";
209  case BCLog::Level::Info:
210  return "info";
212  return "warning";
213  case BCLog::Level::Error:
214  return "error";
215  case BCLog::Level::None:
216  return "";
217  }
218  assert(false);
219 }
220 
221 std::string LogCategoryToStr(BCLog::LogFlags category)
222 {
223  // Each log category string representation should sync with LogCategories
224  switch (category) {
226  return "";
227  case BCLog::LogFlags::NET:
228  return "net";
230  return "tor";
232  return "mempool";
234  return "http";
236  return "bench";
237  case BCLog::LogFlags::ZMQ:
238  return "zmq";
240  return "walletdb";
241  case BCLog::LogFlags::RPC:
242  return "rpc";
244  return "estimatefee";
246  return "addrman";
248  return "selectcoins";
249  case BCLog::LogFlags::REINDEX:
250  return "reindex";
252  return "cmpctblock";
254  return "rand";
256  return "prune";
258  return "proxy";
260  return "mempoolrej";
262  return "libevent";
264  return "coindb";
265  case BCLog::LogFlags::QT:
266  return "qt";
268  return "leveldb";
270  return "validation";
272  return "i2p";
274  return "ipc";
275 #ifdef DEBUG_LOCKCONTENTION
277  return "lock";
278 #endif
280  return "util";
282  return "blockstorage";
284  return "all";
285  }
286  assert(false);
287 }
288 
289 static std::optional<BCLog::Level> GetLogLevel(const std::string& level_str)
290 {
291  if (level_str == "trace") {
292  return BCLog::Level::Trace;
293  } else if (level_str == "debug") {
294  return BCLog::Level::Debug;
295  } else if (level_str == "info") {
296  return BCLog::Level::Info;
297  } else if (level_str == "warning") {
298  return BCLog::Level::Warning;
299  } else if (level_str == "error") {
300  return BCLog::Level::Error;
301  } else if (level_str == "none") {
302  return BCLog::Level::None;
303  } else {
304  return std::nullopt;
305  }
306 }
307 
308 std::vector<LogCategory> BCLog::Logger::LogCategoriesList() const
309 {
310  // Sort log categories by alphabetical order.
311  std::array<CLogCategoryDesc, std::size(LogCategories)> categories;
312  std::copy(std::begin(LogCategories), std::end(LogCategories), categories.begin());
313  std::sort(categories.begin(), categories.end(), [](auto a, auto b) { return a.category < b.category; });
314 
315  std::vector<LogCategory> ret;
316  for (const CLogCategoryDesc& category_desc : categories) {
317  if (category_desc.flag == BCLog::NONE || category_desc.flag == BCLog::ALL) continue;
318  LogCategory catActive;
319  catActive.category = category_desc.category;
320  catActive.active = WillLogCategory(category_desc.flag);
321  ret.push_back(catActive);
322  }
323  return ret;
324 }
325 
327 static constexpr std::array<BCLog::Level, 3> LogLevelsList()
328 {
330 }
331 
333 {
334  const auto& levels = LogLevelsList();
335  return Join(std::vector<BCLog::Level>{levels.begin(), levels.end()}, ", ", [this](BCLog::Level level) { return LogLevelToStr(level); });
336 }
337 
338 std::string BCLog::Logger::LogTimestampStr(const std::string& str)
339 {
340  std::string strStamped;
341 
342  if (!m_log_timestamps)
343  return str;
344 
345  if (m_started_new_line) {
346  int64_t nTimeMicros = GetTimeMicros();
347  strStamped = FormatISO8601DateTime(nTimeMicros/1000000);
348  if (m_log_time_micros) {
349  strStamped.pop_back();
350  strStamped += strprintf(".%06dZ", nTimeMicros%1000000);
351  }
352  std::chrono::seconds mocktime = GetMockTime();
353  if (mocktime > 0s) {
354  strStamped += " (mocktime: " + FormatISO8601DateTime(count_seconds(mocktime)) + ")";
355  }
356  strStamped += ' ' + str;
357  } else
358  strStamped = str;
359 
360  return strStamped;
361 }
362 
363 namespace BCLog {
371  std::string LogEscapeMessage(const std::string& str) {
372  std::string ret;
373  for (char ch_in : str) {
374  uint8_t ch = (uint8_t)ch_in;
375  if ((ch >= 32 || ch == '\n') && ch != '\x7f') {
376  ret += ch_in;
377  } else {
378  ret += strprintf("\\x%02x", ch);
379  }
380  }
381  return ret;
382  }
383 } // namespace BCLog
384 
385 void BCLog::Logger::LogPrintStr(const std::string& str, const std::string& logging_function, const std::string& source_file, int source_line, BCLog::LogFlags category, BCLog::Level level)
386 {
387  StdLockGuard scoped_lock(m_cs);
388  std::string str_prefixed = LogEscapeMessage(str);
389 
390  if ((category != LogFlags::NONE || level != Level::None) && m_started_new_line) {
391  std::string s{"["};
392 
393  if (category != LogFlags::NONE) {
394  s += LogCategoryToStr(category);
395  }
396 
397  if (category != LogFlags::NONE && level != Level::None) {
398  // Only add separator if both flag and level are not NONE
399  s += ":";
400  }
401 
402  if (level != Level::None) {
403  s += LogLevelToStr(level);
404  }
405 
406  s += "] ";
407  str_prefixed.insert(0, s);
408  }
409 
410  if (m_log_sourcelocations && m_started_new_line) {
411  str_prefixed.insert(0, "[" + RemovePrefix(source_file, "./") + ":" + ToString(source_line) + "] [" + logging_function + "] ");
412  }
413 
414  if (m_log_threadnames && m_started_new_line) {
415  const auto& threadname = util::ThreadGetInternalName();
416  str_prefixed.insert(0, "[" + (threadname.empty() ? "unknown" : threadname) + "] ");
417  }
418 
419  str_prefixed = LogTimestampStr(str_prefixed);
420 
421  m_started_new_line = !str.empty() && str[str.size()-1] == '\n';
422 
423  if (m_buffering) {
424  // buffer if we haven't started logging yet
425  m_msgs_before_open.push_back(str_prefixed);
426  return;
427  }
428 
429  if (m_print_to_console) {
430  // print to console
431  fwrite(str_prefixed.data(), 1, str_prefixed.size(), stdout);
432  fflush(stdout);
433  }
434  for (const auto& cb : m_print_callbacks) {
435  cb(str_prefixed);
436  }
437  if (m_print_to_file) {
438  assert(m_fileout != nullptr);
439 
440  // reopen the log file, if requested
441  if (m_reopen_file) {
442  m_reopen_file = false;
443  FILE* new_fileout = fsbridge::fopen(m_file_path, "a");
444  if (new_fileout) {
445  setbuf(new_fileout, nullptr); // unbuffered
446  fclose(m_fileout);
447  m_fileout = new_fileout;
448  }
449  }
450  FileWriteStr(str_prefixed, m_fileout);
451  }
452 }
453 
455 {
456  // Amount of debug.log to save at end when shrinking (must fit in memory)
457  constexpr size_t RECENT_DEBUG_HISTORY_SIZE = 10 * 1000000;
458 
459  assert(!m_file_path.empty());
460 
461  // Scroll debug.log if it's getting too big
462  FILE* file = fsbridge::fopen(m_file_path, "r");
463 
464  // Special files (e.g. device nodes) may not have a size.
465  size_t log_size = 0;
466  try {
467  log_size = fs::file_size(m_file_path);
468  } catch (const fs::filesystem_error&) {}
469 
470  // If debug.log file is more than 10% bigger the RECENT_DEBUG_HISTORY_SIZE
471  // trim it down by saving only the last RECENT_DEBUG_HISTORY_SIZE bytes
472  if (file && log_size > 11 * (RECENT_DEBUG_HISTORY_SIZE / 10))
473  {
474  // Restart the file with some of the end
475  std::vector<char> vch(RECENT_DEBUG_HISTORY_SIZE, 0);
476  if (fseek(file, -((long)vch.size()), SEEK_END)) {
477  LogPrintf("Failed to shrink debug log file: fseek(...) failed\n");
478  fclose(file);
479  return;
480  }
481  int nBytes = fread(vch.data(), 1, vch.size(), file);
482  fclose(file);
483 
484  file = fsbridge::fopen(m_file_path, "w");
485  if (file)
486  {
487  fwrite(vch.data(), 1, nBytes, file);
488  fclose(file);
489  }
490  }
491  else if (file != nullptr)
492  fclose(file);
493 }
494 
495 bool BCLog::Logger::SetLogLevel(const std::string& level_str)
496 {
497  const auto level = GetLogLevel(level_str);
498  if (!level.has_value() || level.value() > MAX_USER_SETABLE_SEVERITY_LEVEL) return false;
499  m_log_level = level.value();
500  return true;
501 }
502 
503 bool BCLog::Logger::SetCategoryLogLevel(const std::string& category_str, const std::string& level_str)
504 {
505  BCLog::LogFlags flag;
506  if (!GetLogCategory(flag, category_str)) return false;
507 
508  const auto level = GetLogLevel(level_str);
509  if (!level.has_value() || level.value() > MAX_USER_SETABLE_SEVERITY_LEVEL) return false;
510 
511  StdLockGuard scoped_lock(m_cs);
512  m_category_log_levels[flag] = level.value();
513  return true;
514 }
void LogPrintStr(const std::string &str, const std::string &logging_function, const std::string &source_file, int source_line, BCLog::LogFlags category, BCLog::Level level)
Send a string to the log output.
Definition: logging.cpp:385
void EnableCategory(LogFlags flag)
Definition: logging.cpp:96
int ret
StdMutex m_cs
Definition: logging.h:84
constexpr auto MAX_USER_SETABLE_SEVERITY_LEVEL
Definition: logging.cpp:18
BCLog::Logger & LogInstance()
Definition: logging.cpp:20
std::chrono::seconds GetMockTime()
For testing.
Definition: time.cpp:102
assert(!tx.IsCoinBase())
FILE * fopen(const fs::path &p, const char *mode)
Definition: fs.cpp:25
void SetCategoryLogLevel(const std::unordered_map< LogFlags, Level > &levels)
Definition: logging.h:161
fs::path m_file_path
Definition: logging.h:121
Definition: timer.h:18
#define strprintf
Format arguments and return the string or write to given std::ostream (see tinyformat::format doc for...
Definition: tinyformat.h:1164
std::string LogLevelToStr(BCLog::Level level) const
Returns the string representation of a log level.
Definition: logging.cpp:202
BCLog::LogFlags flag
Definition: logging.cpp:146
static constexpr std::array< BCLog::Level, 3 > LogLevelsList()
Log severity levels that can be selected by the user.
Definition: logging.cpp:327
std::string FormatISO8601DateTime(int64_t nTime)
ISO 8601 formatting is preferred.
Definition: time.cpp:119
std::string LogCategoryToStr(BCLog::LogFlags category)
Definition: logging.cpp:221
bool m_print_to_console
Definition: logging.h:113
bool m_print_to_file
Definition: logging.h:114
std::string ToString(const T &t)
Locale-independent version of std::to_string.
Definition: string.h:109
std::string category
Definition: logging.cpp:147
std::string category
Definition: logging.h:33
#define LOCK(cs)
Definition: sync.h:261
static std::optional< BCLog::Level > GetLogLevel(const std::string &level_str)
Definition: logging.cpp:289
void DisableCategory(LogFlags flag)
Definition: logging.cpp:109
void SetLogLevel(Level level)
Definition: logging.h:169
bool WillLogCategory(LogFlags category) const
Definition: logging.cpp:122
Level
Definition: logging.h:71
constexpr int64_t count_seconds(std::chrono::seconds t)
Definition: time.h:54
void DisconnectTestLogger()
Only for testing.
Definition: logging.cpp:87
bool StartLogging()
Start logging (and flush all buffered messages)
Definition: logging.cpp:48
bool GetLogCategory(BCLog::LogFlags &flag, const std::string &str)
Return true if str parses as a log category and set the flag.
Definition: logging.cpp:187
int64_t GetTimeMicros()
Returns the system time (not mockable)
Definition: time.cpp:112
const std::string & ThreadGetInternalName()
Get the thread&#39;s internal (in-memory) name; used e.g.
Definition: threadnames.cpp:55
auto Join(const C &container, const S &separator, UnaryOp unary_op)
Join all container items.
Definition: string.h:68
static int FileWriteStr(const std::string &str, FILE *fp)
Definition: logging.cpp:43
const CLogCategoryDesc LogCategories[]
Definition: logging.cpp:150
bool fLogIPs
Definition: logging.cpp:41
bool active
Definition: logging.h:34
LogFlags
Definition: logging.h:38
std::string LogLevelsString() const
Returns a string with all user-selectable log levels.
Definition: logging.cpp:332
std::vector< LogCategory > LogCategoriesList() const
Returns a vector of the log categories in alphabetical order.
Definition: logging.cpp:308
std::string RemovePrefix(std::string_view str, std::string_view prefix)
Definition: string.h:54
static const bool DEFAULT_LOGIPS
Definition: logging.h:24
std::string LogEscapeMessage(const std::string &str)
Belts and suspenders: make sure outgoing log messages don&#39;t contain potentially suspicious characters...
Definition: logging.cpp:371
#define LogPrintf(...)
Definition: logging.h:234
const char *const DEFAULT_DEBUGLOGFILE
Definition: logging.cpp:17
void ShrinkDebugFile()
Definition: logging.cpp:454
std::string LogTimestampStr(const std::string &str)
Definition: logging.cpp:338
bool WillLogCategoryLevel(LogFlags category, Level level) const
Definition: logging.cpp:127
bool DefaultShrinkDebugFile() const
Definition: logging.cpp:140