Bitcoin Core  24.99.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 <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::TXRECONCILIATION, "txreconciliation"},
184  {BCLog::SCAN, "scan"},
185  {BCLog::ALL, "1"},
186  {BCLog::ALL, "all"},
187 };
188 
189 bool GetLogCategory(BCLog::LogFlags& flag, const std::string& str)
190 {
191  if (str.empty()) {
192  flag = BCLog::ALL;
193  return true;
194  }
195  for (const CLogCategoryDesc& category_desc : LogCategories) {
196  if (category_desc.category == str) {
197  flag = category_desc.flag;
198  return true;
199  }
200  }
201  return false;
202 }
203 
205 {
206  switch (level) {
207  case BCLog::Level::Trace:
208  return "trace";
209  case BCLog::Level::Debug:
210  return "debug";
211  case BCLog::Level::Info:
212  return "info";
214  return "warning";
215  case BCLog::Level::Error:
216  return "error";
217  case BCLog::Level::None:
218  return "";
219  }
220  assert(false);
221 }
222 
223 std::string LogCategoryToStr(BCLog::LogFlags category)
224 {
225  // Each log category string representation should sync with LogCategories
226  switch (category) {
228  return "";
229  case BCLog::LogFlags::NET:
230  return "net";
232  return "tor";
234  return "mempool";
236  return "http";
238  return "bench";
239  case BCLog::LogFlags::ZMQ:
240  return "zmq";
242  return "walletdb";
243  case BCLog::LogFlags::RPC:
244  return "rpc";
246  return "estimatefee";
248  return "addrman";
250  return "selectcoins";
252  return "reindex";
254  return "cmpctblock";
256  return "rand";
258  return "prune";
260  return "proxy";
262  return "mempoolrej";
264  return "libevent";
266  return "coindb";
267  case BCLog::LogFlags::QT:
268  return "qt";
270  return "leveldb";
272  return "validation";
274  return "i2p";
276  return "ipc";
277 #ifdef DEBUG_LOCKCONTENTION
279  return "lock";
280 #endif
282  return "util";
284  return "blockstorage";
286  return "txreconciliation";
288  return "scan";
290  return "all";
291  }
292  assert(false);
293 }
294 
295 static std::optional<BCLog::Level> GetLogLevel(const std::string& level_str)
296 {
297  if (level_str == "trace") {
298  return BCLog::Level::Trace;
299  } else if (level_str == "debug") {
300  return BCLog::Level::Debug;
301  } else if (level_str == "info") {
302  return BCLog::Level::Info;
303  } else if (level_str == "warning") {
304  return BCLog::Level::Warning;
305  } else if (level_str == "error") {
306  return BCLog::Level::Error;
307  } else if (level_str == "none") {
308  return BCLog::Level::None;
309  } else {
310  return std::nullopt;
311  }
312 }
313 
314 std::vector<LogCategory> BCLog::Logger::LogCategoriesList() const
315 {
316  // Sort log categories by alphabetical order.
317  std::array<CLogCategoryDesc, std::size(LogCategories)> categories;
318  std::copy(std::begin(LogCategories), std::end(LogCategories), categories.begin());
319  std::sort(categories.begin(), categories.end(), [](auto a, auto b) { return a.category < b.category; });
320 
321  std::vector<LogCategory> ret;
322  for (const CLogCategoryDesc& category_desc : categories) {
323  if (category_desc.flag == BCLog::NONE || category_desc.flag == BCLog::ALL) continue;
324  LogCategory catActive;
325  catActive.category = category_desc.category;
326  catActive.active = WillLogCategory(category_desc.flag);
327  ret.push_back(catActive);
328  }
329  return ret;
330 }
331 
333 static constexpr std::array<BCLog::Level, 3> LogLevelsList()
334 {
336 }
337 
339 {
340  const auto& levels = LogLevelsList();
341  return Join(std::vector<BCLog::Level>{levels.begin(), levels.end()}, ", ", [this](BCLog::Level level) { return LogLevelToStr(level); });
342 }
343 
344 std::string BCLog::Logger::LogTimestampStr(const std::string& str)
345 {
346  std::string strStamped;
347 
348  if (!m_log_timestamps)
349  return str;
350 
351  if (m_started_new_line) {
352  const auto now{SystemClock::now()};
353  const auto now_seconds{std::chrono::time_point_cast<std::chrono::seconds>(now)};
354  strStamped = FormatISO8601DateTime(TicksSinceEpoch<std::chrono::seconds>(now_seconds));
355  if (m_log_time_micros) {
356  strStamped.pop_back();
357  strStamped += strprintf(".%06dZ", Ticks<std::chrono::microseconds>(now - now_seconds));
358  }
359  std::chrono::seconds mocktime = GetMockTime();
360  if (mocktime > 0s) {
361  strStamped += " (mocktime: " + FormatISO8601DateTime(count_seconds(mocktime)) + ")";
362  }
363  strStamped += ' ' + str;
364  } else
365  strStamped = str;
366 
367  return strStamped;
368 }
369 
370 namespace BCLog {
378  std::string LogEscapeMessage(const std::string& str) {
379  std::string ret;
380  for (char ch_in : str) {
381  uint8_t ch = (uint8_t)ch_in;
382  if ((ch >= 32 || ch == '\n') && ch != '\x7f') {
383  ret += ch_in;
384  } else {
385  ret += strprintf("\\x%02x", ch);
386  }
387  }
388  return ret;
389  }
390 } // namespace BCLog
391 
392 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)
393 {
394  StdLockGuard scoped_lock(m_cs);
395  std::string str_prefixed = LogEscapeMessage(str);
396 
397  if ((category != LogFlags::NONE || level != Level::None) && m_started_new_line) {
398  std::string s{"["};
399 
400  if (category != LogFlags::NONE) {
401  s += LogCategoryToStr(category);
402  }
403 
404  if (category != LogFlags::NONE && level != Level::None) {
405  // Only add separator if both flag and level are not NONE
406  s += ":";
407  }
408 
409  if (level != Level::None) {
410  s += LogLevelToStr(level);
411  }
412 
413  s += "] ";
414  str_prefixed.insert(0, s);
415  }
416 
417  if (m_log_sourcelocations && m_started_new_line) {
418  str_prefixed.insert(0, "[" + RemovePrefix(source_file, "./") + ":" + ToString(source_line) + "] [" + logging_function + "] ");
419  }
420 
421  if (m_log_threadnames && m_started_new_line) {
422  const auto& threadname = util::ThreadGetInternalName();
423  str_prefixed.insert(0, "[" + (threadname.empty() ? "unknown" : threadname) + "] ");
424  }
425 
426  str_prefixed = LogTimestampStr(str_prefixed);
427 
428  m_started_new_line = !str.empty() && str[str.size()-1] == '\n';
429 
430  if (m_buffering) {
431  // buffer if we haven't started logging yet
432  m_msgs_before_open.push_back(str_prefixed);
433  return;
434  }
435 
436  if (m_print_to_console) {
437  // print to console
438  fwrite(str_prefixed.data(), 1, str_prefixed.size(), stdout);
439  fflush(stdout);
440  }
441  for (const auto& cb : m_print_callbacks) {
442  cb(str_prefixed);
443  }
444  if (m_print_to_file) {
445  assert(m_fileout != nullptr);
446 
447  // reopen the log file, if requested
448  if (m_reopen_file) {
449  m_reopen_file = false;
450  FILE* new_fileout = fsbridge::fopen(m_file_path, "a");
451  if (new_fileout) {
452  setbuf(new_fileout, nullptr); // unbuffered
453  fclose(m_fileout);
454  m_fileout = new_fileout;
455  }
456  }
457  FileWriteStr(str_prefixed, m_fileout);
458  }
459 }
460 
462 {
463  // Amount of debug.log to save at end when shrinking (must fit in memory)
464  constexpr size_t RECENT_DEBUG_HISTORY_SIZE = 10 * 1000000;
465 
466  assert(!m_file_path.empty());
467 
468  // Scroll debug.log if it's getting too big
469  FILE* file = fsbridge::fopen(m_file_path, "r");
470 
471  // Special files (e.g. device nodes) may not have a size.
472  size_t log_size = 0;
473  try {
474  log_size = fs::file_size(m_file_path);
475  } catch (const fs::filesystem_error&) {}
476 
477  // If debug.log file is more than 10% bigger the RECENT_DEBUG_HISTORY_SIZE
478  // trim it down by saving only the last RECENT_DEBUG_HISTORY_SIZE bytes
479  if (file && log_size > 11 * (RECENT_DEBUG_HISTORY_SIZE / 10))
480  {
481  // Restart the file with some of the end
482  std::vector<char> vch(RECENT_DEBUG_HISTORY_SIZE, 0);
483  if (fseek(file, -((long)vch.size()), SEEK_END)) {
484  LogPrintf("Failed to shrink debug log file: fseek(...) failed\n");
485  fclose(file);
486  return;
487  }
488  int nBytes = fread(vch.data(), 1, vch.size(), file);
489  fclose(file);
490 
491  file = fsbridge::fopen(m_file_path, "w");
492  if (file)
493  {
494  fwrite(vch.data(), 1, nBytes, file);
495  fclose(file);
496  }
497  }
498  else if (file != nullptr)
499  fclose(file);
500 }
501 
502 bool BCLog::Logger::SetLogLevel(const std::string& level_str)
503 {
504  const auto level = GetLogLevel(level_str);
505  if (!level.has_value() || level.value() > MAX_USER_SETABLE_SEVERITY_LEVEL) return false;
506  m_log_level = level.value();
507  return true;
508 }
509 
510 bool BCLog::Logger::SetCategoryLogLevel(const std::string& category_str, const std::string& level_str)
511 {
512  BCLog::LogFlags flag;
513  if (!GetLogCategory(flag, category_str)) return false;
514 
515  const auto level = GetLogLevel(level_str);
516  if (!level.has_value() || level.value() > MAX_USER_SETABLE_SEVERITY_LEVEL) return false;
517 
518  StdLockGuard scoped_lock(m_cs);
519  m_category_log_levels[flag] = level.value();
520  return true;
521 }
int ret
bool WillLogCategory(LogFlags category) const
Definition: logging.cpp:122
std::string LogTimestampStr(const std::string &str)
Definition: logging.cpp:344
void DisconnectTestLogger()
Only for testing.
Definition: logging.cpp:87
bool DefaultShrinkDebugFile() const
Definition: logging.cpp:140
void SetLogLevel(Level level)
Definition: logging.h:171
bool WillLogCategoryLevel(LogFlags category, Level level) const
Definition: logging.cpp:127
fs::path m_file_path
Definition: logging.h:123
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:392
std::vector< LogCategory > LogCategoriesList() const
Returns a vector of the log categories in alphabetical order.
Definition: logging.cpp:314
void EnableCategory(LogFlags flag)
Definition: logging.cpp:96
bool StartLogging()
Start logging (and flush all buffered messages)
Definition: logging.cpp:48
std::string LogLevelToStr(BCLog::Level level) const
Returns the string representation of a log level.
Definition: logging.cpp:204
std::string LogLevelsString() const
Returns a string with all user-selectable log levels.
Definition: logging.cpp:338
void ShrinkDebugFile()
Definition: logging.cpp:461
bool m_print_to_file
Definition: logging.h:116
void SetCategoryLogLevel(const std::unordered_map< LogFlags, Level > &levels)
Definition: logging.h:163
bool m_print_to_console
Definition: logging.h:115
StdMutex m_cs
Definition: logging.h:86
void DisableCategory(LogFlags flag)
Definition: logging.cpp:109
const CLogCategoryDesc LogCategories[]
Definition: logging.cpp:150
static constexpr std::array< BCLog::Level, 3 > LogLevelsList()
Log severity levels that can be selected by the user.
Definition: logging.cpp:333
std::string LogCategoryToStr(BCLog::LogFlags category)
Definition: logging.cpp:223
static int FileWriteStr(const std::string &str, FILE *fp)
Definition: logging.cpp:43
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:189
bool fLogIPs
Definition: logging.cpp:41
const char *const DEFAULT_DEBUGLOGFILE
Definition: logging.cpp:17
static std::optional< BCLog::Level > GetLogLevel(const std::string &level_str)
Definition: logging.cpp:295
constexpr auto MAX_USER_SETABLE_SEVERITY_LEVEL
Definition: logging.cpp:18
BCLog::Logger & LogInstance()
Definition: logging.cpp:20
static const bool DEFAULT_LOGIPS
Definition: logging.h:24
#define LogPrintf(...)
Definition: logging.h:236
Definition: timer.h:19
Level
Definition: logging.h:73
std::string LogEscapeMessage(const std::string &str)
Belts and suspenders: make sure outgoing log messages don't contain potentially suspicious characters...
Definition: logging.cpp:378
LogFlags
Definition: logging.h:38
@ ESTIMATEFEE
Definition: logging.h:48
@ TXRECONCILIATION
Definition: logging.h:69
@ RAND
Definition: logging.h:53
@ COINDB
Definition: logging.h:58
@ REINDEX
Definition: logging.h:51
@ WALLETDB
Definition: logging.h:46
@ SCAN
Definition: logging.h:70
@ ADDRMAN
Definition: logging.h:49
@ ALL
Definition: logging.h:71
@ RPC
Definition: logging.h:47
@ HTTP
Definition: logging.h:43
@ LEVELDB
Definition: logging.h:60
@ NONE
Definition: logging.h:39
@ VALIDATION
Definition: logging.h:61
@ MEMPOOLREJ
Definition: logging.h:56
@ PRUNE
Definition: logging.h:54
@ TOR
Definition: logging.h:41
@ LIBEVENT
Definition: logging.h:57
@ CMPCTBLOCK
Definition: logging.h:52
@ PROXY
Definition: logging.h:55
@ ZMQ
Definition: logging.h:45
@ IPC
Definition: logging.h:63
@ MEMPOOL
Definition: logging.h:42
@ SELECTCOINS
Definition: logging.h:50
@ I2P
Definition: logging.h:62
@ BENCH
Definition: logging.h:44
@ NET
Definition: logging.h:40
@ UTIL
Definition: logging.h:67
@ QT
Definition: logging.h:59
@ BLOCKSTORE
Definition: logging.h:68
FILE * fopen(const fs::path &p, const char *mode)
Definition: fs.cpp:25
const std::string & ThreadGetInternalName()
Get the thread's internal (in-memory) name; used e.g.
Definition: threadnames.cpp:55
std::string RemovePrefix(std::string_view str, std::string_view prefix)
Definition: string.h:54
std::string ToString(const T &t)
Locale-independent version of std::to_string.
Definition: string.h:109
auto Join(const C &container, const S &separator, UnaryOp unary_op)
Join all container items.
Definition: string.h:68
BCLog::LogFlags flag
Definition: logging.cpp:146
std::string category
Definition: logging.cpp:147
bool active
Definition: logging.h:34
std::string category
Definition: logging.h:33
#define LOCK(cs)
Definition: sync.h:258
std::chrono::seconds GetMockTime()
For testing.
Definition: time.cpp:100
std::string FormatISO8601DateTime(int64_t nTime)
ISO 8601 formatting is preferred.
Definition: time.cpp:112
constexpr int64_t count_seconds(std::chrono::seconds t)
Definition: time.h:56
#define strprintf
Format arguments and return the string or write to given std::ostream (see tinyformat::format doc for...
Definition: tinyformat.h:1162
assert(!tx.IsCoinBase())