Bitcoin Core  26.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-2022 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 <logging.h>
7 #include <util/fs.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::BLOCKSTORAGE, "blockstorage"},
183  {BCLog::TXRECONCILIATION, "txreconciliation"},
184  {BCLog::SCAN, "scan"},
185  {BCLog::TXPACKAGES, "txpackages"},
186  {BCLog::ALL, "1"},
187  {BCLog::ALL, "all"},
188 };
189 
190 bool GetLogCategory(BCLog::LogFlags& flag, const std::string& str)
191 {
192  if (str.empty()) {
193  flag = BCLog::ALL;
194  return true;
195  }
196  for (const CLogCategoryDesc& category_desc : LogCategories) {
197  if (category_desc.category == str) {
198  flag = category_desc.flag;
199  return true;
200  }
201  }
202  return false;
203 }
204 
206 {
207  switch (level) {
208  case BCLog::Level::Trace:
209  return "trace";
210  case BCLog::Level::Debug:
211  return "debug";
212  case BCLog::Level::Info:
213  return "info";
215  return "warning";
216  case BCLog::Level::Error:
217  return "error";
218  case BCLog::Level::None:
219  return "";
220  }
221  assert(false);
222 }
223 
224 std::string LogCategoryToStr(BCLog::LogFlags category)
225 {
226  // Each log category string representation should sync with LogCategories
227  switch (category) {
229  return "";
231  return "net";
233  return "tor";
235  return "mempool";
237  return "http";
239  return "bench";
240  case BCLog::LogFlags::ZMQ:
241  return "zmq";
243  return "walletdb";
244  case BCLog::LogFlags::RPC:
245  return "rpc";
247  return "estimatefee";
249  return "addrman";
251  return "selectcoins";
253  return "reindex";
255  return "cmpctblock";
257  return "rand";
259  return "prune";
261  return "proxy";
263  return "mempoolrej";
265  return "libevent";
267  return "coindb";
268  case BCLog::LogFlags::QT:
269  return "qt";
271  return "leveldb";
273  return "validation";
275  return "i2p";
277  return "ipc";
278 #ifdef DEBUG_LOCKCONTENTION
280  return "lock";
281 #endif
283  return "util";
285  return "blockstorage";
287  return "txreconciliation";
289  return "scan";
291  return "txpackages";
293  return "all";
294  }
295  assert(false);
296 }
297 
298 static std::optional<BCLog::Level> GetLogLevel(const std::string& level_str)
299 {
300  if (level_str == "trace") {
301  return BCLog::Level::Trace;
302  } else if (level_str == "debug") {
303  return BCLog::Level::Debug;
304  } else if (level_str == "info") {
305  return BCLog::Level::Info;
306  } else if (level_str == "warning") {
307  return BCLog::Level::Warning;
308  } else if (level_str == "error") {
309  return BCLog::Level::Error;
310  } else if (level_str == "none") {
311  return BCLog::Level::None;
312  } else {
313  return std::nullopt;
314  }
315 }
316 
317 std::vector<LogCategory> BCLog::Logger::LogCategoriesList() const
318 {
319  // Sort log categories by alphabetical order.
320  std::array<CLogCategoryDesc, std::size(LogCategories)> categories;
321  std::copy(std::begin(LogCategories), std::end(LogCategories), categories.begin());
322  std::sort(categories.begin(), categories.end(), [](auto a, auto b) { return a.category < b.category; });
323 
324  std::vector<LogCategory> ret;
325  for (const CLogCategoryDesc& category_desc : categories) {
326  if (category_desc.flag == BCLog::NONE || category_desc.flag == BCLog::ALL) continue;
327  LogCategory catActive;
328  catActive.category = category_desc.category;
329  catActive.active = WillLogCategory(category_desc.flag);
330  ret.push_back(catActive);
331  }
332  return ret;
333 }
334 
336 static constexpr std::array<BCLog::Level, 3> LogLevelsList()
337 {
339 }
340 
342 {
343  const auto& levels = LogLevelsList();
344  return Join(std::vector<BCLog::Level>{levels.begin(), levels.end()}, ", ", [this](BCLog::Level level) { return LogLevelToStr(level); });
345 }
346 
347 std::string BCLog::Logger::LogTimestampStr(const std::string& str)
348 {
349  std::string strStamped;
350 
351  if (!m_log_timestamps)
352  return str;
353 
354  if (m_started_new_line) {
355  const auto now{SystemClock::now()};
356  const auto now_seconds{std::chrono::time_point_cast<std::chrono::seconds>(now)};
357  strStamped = FormatISO8601DateTime(TicksSinceEpoch<std::chrono::seconds>(now_seconds));
358  if (m_log_time_micros && !strStamped.empty()) {
359  strStamped.pop_back();
360  strStamped += strprintf(".%06dZ", Ticks<std::chrono::microseconds>(now - now_seconds));
361  }
362  std::chrono::seconds mocktime = GetMockTime();
363  if (mocktime > 0s) {
364  strStamped += " (mocktime: " + FormatISO8601DateTime(count_seconds(mocktime)) + ")";
365  }
366  strStamped += ' ' + str;
367  } else
368  strStamped = str;
369 
370  return strStamped;
371 }
372 
373 namespace BCLog {
381  std::string LogEscapeMessage(const std::string& str) {
382  std::string ret;
383  for (char ch_in : str) {
384  uint8_t ch = (uint8_t)ch_in;
385  if ((ch >= 32 || ch == '\n') && ch != '\x7f') {
386  ret += ch_in;
387  } else {
388  ret += strprintf("\\x%02x", ch);
389  }
390  }
391  return ret;
392  }
393 } // namespace BCLog
394 
395 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)
396 {
397  StdLockGuard scoped_lock(m_cs);
398  std::string str_prefixed = LogEscapeMessage(str);
399 
400  if ((category != LogFlags::NONE || level != Level::None) && m_started_new_line) {
401  std::string s{"["};
402 
403  if (category != LogFlags::NONE) {
404  s += LogCategoryToStr(category);
405  }
406 
407  if (category != LogFlags::NONE && level != Level::None) {
408  // Only add separator if both flag and level are not NONE
409  s += ":";
410  }
411 
412  if (level != Level::None) {
413  s += LogLevelToStr(level);
414  }
415 
416  s += "] ";
417  str_prefixed.insert(0, s);
418  }
419 
420  if (m_log_sourcelocations && m_started_new_line) {
421  str_prefixed.insert(0, "[" + RemovePrefix(source_file, "./") + ":" + ToString(source_line) + "] [" + logging_function + "] ");
422  }
423 
424  if (m_log_threadnames && m_started_new_line) {
425  const auto& threadname = util::ThreadGetInternalName();
426  str_prefixed.insert(0, "[" + (threadname.empty() ? "unknown" : threadname) + "] ");
427  }
428 
429  str_prefixed = LogTimestampStr(str_prefixed);
430 
431  m_started_new_line = !str.empty() && str[str.size()-1] == '\n';
432 
433  if (m_buffering) {
434  // buffer if we haven't started logging yet
435  m_msgs_before_open.push_back(str_prefixed);
436  return;
437  }
438 
439  if (m_print_to_console) {
440  // print to console
441  fwrite(str_prefixed.data(), 1, str_prefixed.size(), stdout);
442  fflush(stdout);
443  }
444  for (const auto& cb : m_print_callbacks) {
445  cb(str_prefixed);
446  }
447  if (m_print_to_file) {
448  assert(m_fileout != nullptr);
449 
450  // reopen the log file, if requested
451  if (m_reopen_file) {
452  m_reopen_file = false;
453  FILE* new_fileout = fsbridge::fopen(m_file_path, "a");
454  if (new_fileout) {
455  setbuf(new_fileout, nullptr); // unbuffered
456  fclose(m_fileout);
457  m_fileout = new_fileout;
458  }
459  }
460  FileWriteStr(str_prefixed, m_fileout);
461  }
462 }
463 
465 {
466  // Amount of debug.log to save at end when shrinking (must fit in memory)
467  constexpr size_t RECENT_DEBUG_HISTORY_SIZE = 10 * 1000000;
468 
469  assert(!m_file_path.empty());
470 
471  // Scroll debug.log if it's getting too big
472  FILE* file = fsbridge::fopen(m_file_path, "r");
473 
474  // Special files (e.g. device nodes) may not have a size.
475  size_t log_size = 0;
476  try {
477  log_size = fs::file_size(m_file_path);
478  } catch (const fs::filesystem_error&) {}
479 
480  // If debug.log file is more than 10% bigger the RECENT_DEBUG_HISTORY_SIZE
481  // trim it down by saving only the last RECENT_DEBUG_HISTORY_SIZE bytes
482  if (file && log_size > 11 * (RECENT_DEBUG_HISTORY_SIZE / 10))
483  {
484  // Restart the file with some of the end
485  std::vector<char> vch(RECENT_DEBUG_HISTORY_SIZE, 0);
486  if (fseek(file, -((long)vch.size()), SEEK_END)) {
487  LogPrintf("Failed to shrink debug log file: fseek(...) failed\n");
488  fclose(file);
489  return;
490  }
491  int nBytes = fread(vch.data(), 1, vch.size(), file);
492  fclose(file);
493 
494  file = fsbridge::fopen(m_file_path, "w");
495  if (file)
496  {
497  fwrite(vch.data(), 1, nBytes, file);
498  fclose(file);
499  }
500  }
501  else if (file != nullptr)
502  fclose(file);
503 }
504 
505 bool BCLog::Logger::SetLogLevel(const std::string& level_str)
506 {
507  const auto level = GetLogLevel(level_str);
508  if (!level.has_value() || level.value() > MAX_USER_SETABLE_SEVERITY_LEVEL) return false;
509  m_log_level = level.value();
510  return true;
511 }
512 
513 bool BCLog::Logger::SetCategoryLogLevel(const std::string& category_str, const std::string& level_str)
514 {
515  BCLog::LogFlags flag;
516  if (!GetLogCategory(flag, category_str)) return false;
517 
518  const auto level = GetLogLevel(level_str);
519  if (!level.has_value() || level.value() > MAX_USER_SETABLE_SEVERITY_LEVEL) return false;
520 
521  StdLockGuard scoped_lock(m_cs);
522  m_category_log_levels[flag] = level.value();
523  return true;
524 }
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:395
void EnableCategory(LogFlags flag)
Definition: logging.cpp:96
int ret
StdMutex m_cs
Definition: logging.h:87
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:92
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:164
fs::path m_file_path
Definition: logging.h:124
Definition: timer.h:19
#define strprintf
Format arguments and return the string or write to given std::ostream (see tinyformat::format doc for...
Definition: tinyformat.h:1162
std::string LogLevelToStr(BCLog::Level level) const
Returns the string representation of a log level.
Definition: logging.cpp:205
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:336
std::string FormatISO8601DateTime(int64_t nTime)
ISO 8601 formatting is preferred.
Definition: time.cpp:99
std::string LogCategoryToStr(BCLog::LogFlags category)
Definition: logging.cpp:224
bool m_print_to_console
Definition: logging.h:116
bool m_print_to_file
Definition: logging.h:117
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:258
static std::optional< BCLog::Level > GetLogLevel(const std::string &level_str)
Definition: logging.cpp:298
void DisableCategory(LogFlags flag)
Definition: logging.cpp:109
void SetLogLevel(Level level)
Definition: logging.h:172
bool WillLogCategory(LogFlags category) const
Definition: logging.cpp:122
Level
Definition: logging.h:74
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:190
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:341
std::vector< LogCategory > LogCategoriesList() const
Returns a vector of the log categories in alphabetical order.
Definition: logging.cpp:317
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:381
#define LogPrintf(...)
Definition: logging.h:237
const char *const DEFAULT_DEBUGLOGFILE
Definition: logging.cpp:17
void ShrinkDebugFile()
Definition: logging.cpp:464
std::string LogTimestampStr(const std::string &str)
Definition: logging.cpp:347
bool WillLogCategoryLevel(LogFlags category, Level level) const
Definition: logging.cpp:127
bool DefaultShrinkDebugFile() const
Definition: logging.cpp:140