Bitcoin Core  27.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 <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 <array>
13 #include <map>
14 #include <optional>
15 
16 const char * const DEFAULT_DEBUGLOGFILE = "debug.log";
18 
20 {
36  static BCLog::Logger* g_logger{new BCLog::Logger()};
37  return *g_logger;
38 }
39 
41 
42 static int FileWriteStr(const std::string &str, FILE *fp)
43 {
44  return fwrite(str.data(), 1, str.size(), fp);
45 }
46 
48 {
49  StdLockGuard scoped_lock(m_cs);
50 
51  assert(m_buffering);
52  assert(m_fileout == nullptr);
53 
54  if (m_print_to_file) {
55  assert(!m_file_path.empty());
56  m_fileout = fsbridge::fopen(m_file_path, "a");
57  if (!m_fileout) {
58  return false;
59  }
60 
61  setbuf(m_fileout, nullptr); // unbuffered
62 
63  // Add newlines to the logfile to distinguish this execution from the
64  // last one.
65  FileWriteStr("\n\n\n\n\n", m_fileout);
66  }
67 
68  // dump buffered messages from before we opened the log
69  m_buffering = false;
70  while (!m_msgs_before_open.empty()) {
71  const std::string& s = m_msgs_before_open.front();
72 
73  if (m_print_to_file) FileWriteStr(s, m_fileout);
74  if (m_print_to_console) fwrite(s.data(), 1, s.size(), stdout);
75  for (const auto& cb : m_print_callbacks) {
76  cb(s);
77  }
78 
79  m_msgs_before_open.pop_front();
80  }
81  if (m_print_to_console) fflush(stdout);
82 
83  return true;
84 }
85 
87 {
88  StdLockGuard scoped_lock(m_cs);
89  m_buffering = true;
90  if (m_fileout != nullptr) fclose(m_fileout);
91  m_fileout = nullptr;
92  m_print_callbacks.clear();
93 }
94 
96 {
97  m_categories |= flag;
98 }
99 
100 bool BCLog::Logger::EnableCategory(const std::string& str)
101 {
102  BCLog::LogFlags flag;
103  if (!GetLogCategory(flag, str)) return false;
104  EnableCategory(flag);
105  return true;
106 }
107 
109 {
110  m_categories &= ~flag;
111 }
112 
113 bool BCLog::Logger::DisableCategory(const std::string& str)
114 {
115  BCLog::LogFlags flag;
116  if (!GetLogCategory(flag, str)) return false;
117  DisableCategory(flag);
118  return true;
119 }
120 
122 {
123  return (m_categories.load(std::memory_order_relaxed) & category) != 0;
124 }
125 
127 {
128  // Log messages at Info, Warning and Error level unconditionally, so that
129  // important troubleshooting information doesn't get lost.
130  if (level >= BCLog::Level::Info) return true;
131 
132  if (!WillLogCategory(category)) return false;
133 
134  StdLockGuard scoped_lock(m_cs);
135  const auto it{m_category_log_levels.find(category)};
136  return level >= (it == m_category_log_levels.end() ? LogLevel() : it->second);
137 }
138 
140 {
141  return m_categories == BCLog::NONE;
142 }
143 
144 static const std::map<std::string, BCLog::LogFlags> LOG_CATEGORIES_BY_STR{
145  {"0", BCLog::NONE},
146  {"", BCLog::NONE},
147  {"net", BCLog::NET},
148  {"tor", BCLog::TOR},
149  {"mempool", BCLog::MEMPOOL},
150  {"http", BCLog::HTTP},
151  {"bench", BCLog::BENCH},
152  {"zmq", BCLog::ZMQ},
153  {"walletdb", BCLog::WALLETDB},
154  {"rpc", BCLog::RPC},
155  {"estimatefee", BCLog::ESTIMATEFEE},
156  {"addrman", BCLog::ADDRMAN},
157  {"selectcoins", BCLog::SELECTCOINS},
158  {"reindex", BCLog::REINDEX},
159  {"cmpctblock", BCLog::CMPCTBLOCK},
160  {"rand", BCLog::RAND},
161  {"prune", BCLog::PRUNE},
162  {"proxy", BCLog::PROXY},
163  {"mempoolrej", BCLog::MEMPOOLREJ},
164  {"libevent", BCLog::LIBEVENT},
165  {"coindb", BCLog::COINDB},
166  {"qt", BCLog::QT},
167  {"leveldb", BCLog::LEVELDB},
168  {"validation", BCLog::VALIDATION},
169  {"i2p", BCLog::I2P},
170  {"ipc", BCLog::IPC},
171 #ifdef DEBUG_LOCKCONTENTION
172  {"lock", BCLog::LOCK},
173 #endif
174  {"blockstorage", BCLog::BLOCKSTORAGE},
175  {"txreconciliation", BCLog::TXRECONCILIATION},
176  {"scan", BCLog::SCAN},
177  {"txpackages", BCLog::TXPACKAGES},
178  {"1", BCLog::ALL},
179  {"all", BCLog::ALL},
180 };
181 
182 static const std::unordered_map<BCLog::LogFlags, std::string> LOG_CATEGORIES_BY_FLAG{
183  // Swap keys and values from LOG_CATEGORIES_BY_STR.
184  [](const std::map<std::string, BCLog::LogFlags>& in) {
185  std::unordered_map<BCLog::LogFlags, std::string> out;
186  for (const auto& [k, v] : in) {
187  switch (v) {
188  case BCLog::NONE: out.emplace(BCLog::NONE, ""); break;
189  case BCLog::ALL: out.emplace(BCLog::ALL, "all"); break;
190  default: out.emplace(v, k);
191  }
192  }
193  return out;
195 };
196 
197 bool GetLogCategory(BCLog::LogFlags& flag, const std::string& str)
198 {
199  if (str.empty()) {
200  flag = BCLog::ALL;
201  return true;
202  }
203  auto it = LOG_CATEGORIES_BY_STR.find(str);
204  if (it != LOG_CATEGORIES_BY_STR.end()) {
205  flag = it->second;
206  return true;
207  }
208  return false;
209 }
210 
212 {
213  switch (level) {
214  case BCLog::Level::Trace:
215  return "trace";
216  case BCLog::Level::Debug:
217  return "debug";
218  case BCLog::Level::Info:
219  return "info";
221  return "warning";
222  case BCLog::Level::Error:
223  return "error";
224  }
225  assert(false);
226 }
227 
228 std::string LogCategoryToStr(BCLog::LogFlags category)
229 {
230  auto it = LOG_CATEGORIES_BY_FLAG.find(category);
231  assert(it != LOG_CATEGORIES_BY_FLAG.end());
232  return it->second;
233 }
234 
235 static std::optional<BCLog::Level> GetLogLevel(const std::string& level_str)
236 {
237  if (level_str == "trace") {
238  return BCLog::Level::Trace;
239  } else if (level_str == "debug") {
240  return BCLog::Level::Debug;
241  } else if (level_str == "info") {
242  return BCLog::Level::Info;
243  } else if (level_str == "warning") {
244  return BCLog::Level::Warning;
245  } else if (level_str == "error") {
246  return BCLog::Level::Error;
247  } else {
248  return std::nullopt;
249  }
250 }
251 
252 std::vector<LogCategory> BCLog::Logger::LogCategoriesList() const
253 {
254  std::vector<LogCategory> ret;
255  for (const auto& [category, flag] : LOG_CATEGORIES_BY_STR) {
256  if (flag != BCLog::NONE && flag != BCLog::ALL) {
257  ret.push_back(LogCategory{.category = category, .active = WillLogCategory(flag)});
258  }
259  }
260  return ret;
261 }
262 
264 static constexpr std::array<BCLog::Level, 3> LogLevelsList()
265 {
267 }
268 
270 {
271  const auto& levels = LogLevelsList();
272  return Join(std::vector<BCLog::Level>{levels.begin(), levels.end()}, ", ", [](BCLog::Level level) { return LogLevelToStr(level); });
273 }
274 
275 std::string BCLog::Logger::LogTimestampStr(const std::string& str)
276 {
277  std::string strStamped;
278 
279  if (!m_log_timestamps)
280  return str;
281 
282  if (m_started_new_line) {
283  const auto now{SystemClock::now()};
284  const auto now_seconds{std::chrono::time_point_cast<std::chrono::seconds>(now)};
285  strStamped = FormatISO8601DateTime(TicksSinceEpoch<std::chrono::seconds>(now_seconds));
286  if (m_log_time_micros && !strStamped.empty()) {
287  strStamped.pop_back();
288  strStamped += strprintf(".%06dZ", Ticks<std::chrono::microseconds>(now - now_seconds));
289  }
290  std::chrono::seconds mocktime = GetMockTime();
291  if (mocktime > 0s) {
292  strStamped += " (mocktime: " + FormatISO8601DateTime(count_seconds(mocktime)) + ")";
293  }
294  strStamped += ' ' + str;
295  } else
296  strStamped = str;
297 
298  return strStamped;
299 }
300 
301 namespace BCLog {
309  std::string LogEscapeMessage(const std::string& str) {
310  std::string ret;
311  for (char ch_in : str) {
312  uint8_t ch = (uint8_t)ch_in;
313  if ((ch >= 32 || ch == '\n') && ch != '\x7f') {
314  ret += ch_in;
315  } else {
316  ret += strprintf("\\x%02x", ch);
317  }
318  }
319  return ret;
320  }
321 } // namespace BCLog
322 
323 std::string BCLog::Logger::GetLogPrefix(BCLog::LogFlags category, BCLog::Level level) const
324 {
325  if (category == LogFlags::NONE) category = LogFlags::ALL;
326 
327  const bool has_category{m_always_print_category_level || category != LogFlags::ALL};
328 
329  // If there is no category, Info is implied
330  if (!has_category && level == Level::Info) return {};
331 
332  std::string s{"["};
333  if (has_category) {
334  s += LogCategoryToStr(category);
335  }
336 
337  if (m_always_print_category_level || !has_category || level != Level::Debug) {
338  // If there is a category, Debug is implied, so don't add the level
339 
340  // Only add separator if we have a category
341  if (has_category) s += ":";
342  s += Logger::LogLevelToStr(level);
343  }
344 
345  s += "] ";
346  return s;
347 }
348 
349 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)
350 {
351  StdLockGuard scoped_lock(m_cs);
352  std::string str_prefixed = LogEscapeMessage(str);
353 
354  if (m_started_new_line) {
355  str_prefixed.insert(0, GetLogPrefix(category, level));
356  }
357 
358  if (m_log_sourcelocations && m_started_new_line) {
359  str_prefixed.insert(0, "[" + RemovePrefix(source_file, "./") + ":" + ToString(source_line) + "] [" + logging_function + "] ");
360  }
361 
362  if (m_log_threadnames && m_started_new_line) {
363  const auto& threadname = util::ThreadGetInternalName();
364  str_prefixed.insert(0, "[" + (threadname.empty() ? "unknown" : threadname) + "] ");
365  }
366 
367  str_prefixed = LogTimestampStr(str_prefixed);
368 
369  m_started_new_line = !str.empty() && str[str.size()-1] == '\n';
370 
371  if (m_buffering) {
372  // buffer if we haven't started logging yet
373  m_msgs_before_open.push_back(str_prefixed);
374  return;
375  }
376 
377  if (m_print_to_console) {
378  // print to console
379  fwrite(str_prefixed.data(), 1, str_prefixed.size(), stdout);
380  fflush(stdout);
381  }
382  for (const auto& cb : m_print_callbacks) {
383  cb(str_prefixed);
384  }
385  if (m_print_to_file) {
386  assert(m_fileout != nullptr);
387 
388  // reopen the log file, if requested
389  if (m_reopen_file) {
390  m_reopen_file = false;
391  FILE* new_fileout = fsbridge::fopen(m_file_path, "a");
392  if (new_fileout) {
393  setbuf(new_fileout, nullptr); // unbuffered
394  fclose(m_fileout);
395  m_fileout = new_fileout;
396  }
397  }
398  FileWriteStr(str_prefixed, m_fileout);
399  }
400 }
401 
403 {
404  // Amount of debug.log to save at end when shrinking (must fit in memory)
405  constexpr size_t RECENT_DEBUG_HISTORY_SIZE = 10 * 1000000;
406 
407  assert(!m_file_path.empty());
408 
409  // Scroll debug.log if it's getting too big
410  FILE* file = fsbridge::fopen(m_file_path, "r");
411 
412  // Special files (e.g. device nodes) may not have a size.
413  size_t log_size = 0;
414  try {
415  log_size = fs::file_size(m_file_path);
416  } catch (const fs::filesystem_error&) {}
417 
418  // If debug.log file is more than 10% bigger the RECENT_DEBUG_HISTORY_SIZE
419  // trim it down by saving only the last RECENT_DEBUG_HISTORY_SIZE bytes
420  if (file && log_size > 11 * (RECENT_DEBUG_HISTORY_SIZE / 10))
421  {
422  // Restart the file with some of the end
423  std::vector<char> vch(RECENT_DEBUG_HISTORY_SIZE, 0);
424  if (fseek(file, -((long)vch.size()), SEEK_END)) {
425  LogPrintf("Failed to shrink debug log file: fseek(...) failed\n");
426  fclose(file);
427  return;
428  }
429  int nBytes = fread(vch.data(), 1, vch.size(), file);
430  fclose(file);
431 
432  file = fsbridge::fopen(m_file_path, "w");
433  if (file)
434  {
435  fwrite(vch.data(), 1, nBytes, file);
436  fclose(file);
437  }
438  }
439  else if (file != nullptr)
440  fclose(file);
441 }
442 
443 bool BCLog::Logger::SetLogLevel(const std::string& level_str)
444 {
445  const auto level = GetLogLevel(level_str);
446  if (!level.has_value() || level.value() > MAX_USER_SETABLE_SEVERITY_LEVEL) return false;
447  m_log_level = level.value();
448  return true;
449 }
450 
451 bool BCLog::Logger::SetCategoryLogLevel(const std::string& category_str, const std::string& level_str)
452 {
453  BCLog::LogFlags flag;
454  if (!GetLogCategory(flag, category_str)) return false;
455 
456  const auto level = GetLogLevel(level_str);
457  if (!level.has_value() || level.value() > MAX_USER_SETABLE_SEVERITY_LEVEL) return false;
458 
459  StdLockGuard scoped_lock(m_cs);
460  m_category_log_levels[flag] = level.value();
461  return true;
462 }
int ret
static std::string LogLevelToStr(BCLog::Level level)
Returns the string representation of a log level.
Definition: logging.cpp:211
bool WillLogCategory(LogFlags category) const
Definition: logging.cpp:121
std::string LogTimestampStr(const std::string &str)
Definition: logging.cpp:275
void DisconnectTestLogger()
Only for testing.
Definition: logging.cpp:86
bool DefaultShrinkDebugFile() const
Definition: logging.cpp:139
void SetLogLevel(Level level)
Definition: logging.h:174
bool WillLogCategoryLevel(LogFlags category, Level level) const
Definition: logging.cpp:126
fs::path m_file_path
Definition: logging.h:124
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:349
std::vector< LogCategory > LogCategoriesList() const
Returns a vector of the log categories in alphabetical order.
Definition: logging.cpp:252
void EnableCategory(LogFlags flag)
Definition: logging.cpp:95
bool StartLogging()
Start logging (and flush all buffered messages)
Definition: logging.cpp:47
std::string GetLogPrefix(LogFlags category, Level level) const
Definition: logging.cpp:323
std::string LogLevelsString() const
Returns a string with all user-selectable log levels.
Definition: logging.cpp:269
void ShrinkDebugFile()
Definition: logging.cpp:402
bool m_print_to_file
Definition: logging.h:116
void SetCategoryLogLevel(const std::unordered_map< LogFlags, Level > &levels)
Definition: logging.h:166
bool m_print_to_console
Definition: logging.h:115
StdMutex m_cs
Definition: logging.h:86
void DisableCategory(LogFlags flag)
Definition: logging.cpp:108
static constexpr std::array< BCLog::Level, 3 > LogLevelsList()
Log severity levels that can be selected by the user.
Definition: logging.cpp:264
std::string LogCategoryToStr(BCLog::LogFlags category)
Definition: logging.cpp:228
static int FileWriteStr(const std::string &str, FILE *fp)
Definition: logging.cpp:42
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:197
bool fLogIPs
Definition: logging.cpp:40
static const std::unordered_map< BCLog::LogFlags, std::string > LOG_CATEGORIES_BY_FLAG
Definition: logging.cpp:182
const char *const DEFAULT_DEBUGLOGFILE
Definition: logging.cpp:16
static std::optional< BCLog::Level > GetLogLevel(const std::string &level_str)
Definition: logging.cpp:235
static const std::map< std::string, BCLog::LogFlags > LOG_CATEGORIES_BY_STR
Definition: logging.cpp:144
constexpr auto MAX_USER_SETABLE_SEVERITY_LEVEL
Definition: logging.cpp:17
BCLog::Logger & LogInstance()
Definition: logging.cpp:19
static const bool DEFAULT_LOGIPS
Definition: logging.h:24
#define LogPrintf(...)
Definition: logging.h:244
Definition: timer.h:19
Level
Definition: logging.h:74
std::string LogEscapeMessage(const std::string &str)
Belts and suspenders: make sure outgoing log messages don't contain potentially suspicious characters...
Definition: logging.cpp:309
LogFlags
Definition: logging.h:39
@ ESTIMATEFEE
Definition: logging.h:49
@ TXRECONCILIATION
Definition: logging.h:69
@ RAND
Definition: logging.h:54
@ BLOCKSTORAGE
Definition: logging.h:68
@ COINDB
Definition: logging.h:59
@ REINDEX
Definition: logging.h:52
@ TXPACKAGES
Definition: logging.h:71
@ WALLETDB
Definition: logging.h:47
@ SCAN
Definition: logging.h:70
@ ADDRMAN
Definition: logging.h:50
@ ALL
Definition: logging.h:72
@ RPC
Definition: logging.h:48
@ HTTP
Definition: logging.h:44
@ LEVELDB
Definition: logging.h:61
@ NONE
Definition: logging.h:40
@ VALIDATION
Definition: logging.h:62
@ MEMPOOLREJ
Definition: logging.h:57
@ PRUNE
Definition: logging.h:55
@ TOR
Definition: logging.h:42
@ LIBEVENT
Definition: logging.h:58
@ CMPCTBLOCK
Definition: logging.h:53
@ PROXY
Definition: logging.h:56
@ ZMQ
Definition: logging.h:46
@ IPC
Definition: logging.h:64
@ MEMPOOL
Definition: logging.h:43
@ SELECTCOINS
Definition: logging.h:51
@ I2P
Definition: logging.h:63
@ BENCH
Definition: logging.h:45
@ NET
Definition: logging.h:41
@ QT
Definition: logging.h:60
FILE * fopen(const fs::path &p, const char *mode)
Definition: fs.cpp:26
std::string ThreadGetInternalName()
Get the thread's internal (in-memory) name; used e.g.
Definition: threadnames.cpp:47
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:110
auto Join(const C &container, const S &separator, UnaryOp unary_op)
Join all container items.
Definition: string.h:69
std::string category
Definition: logging.h:34
#define LOCK(cs)
Definition: sync.h:257
std::chrono::seconds GetMockTime()
For testing.
Definition: time.cpp:39
std::string FormatISO8601DateTime(int64_t nTime)
ISO 8601 formatting is preferred.
Definition: time.cpp:46
constexpr int64_t count_seconds(std::chrono::seconds t)
Definition: time.h:54
#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())