Bitcoin Core  22.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-2020 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/threadnames.h>
8 #include <util/string.h>
9 #include <util/time.h>
10 
11 #include <algorithm>
12 #include <array>
13 #include <mutex>
14 
15 const char * const DEFAULT_DEBUGLOGFILE = "debug.log";
16 
18 {
34  static BCLog::Logger* g_logger{new BCLog::Logger()};
35  return *g_logger;
36 }
37 
39 
40 static int FileWriteStr(const std::string &str, FILE *fp)
41 {
42  return fwrite(str.data(), 1, str.size(), fp);
43 }
44 
46 {
47  StdLockGuard scoped_lock(m_cs);
48 
49  assert(m_buffering);
50  assert(m_fileout == nullptr);
51 
52  if (m_print_to_file) {
53  assert(!m_file_path.empty());
54  m_fileout = fsbridge::fopen(m_file_path, "a");
55  if (!m_fileout) {
56  return false;
57  }
58 
59  setbuf(m_fileout, nullptr); // unbuffered
60 
61  // Add newlines to the logfile to distinguish this execution from the
62  // last one.
63  FileWriteStr("\n\n\n\n\n", m_fileout);
64  }
65 
66  // dump buffered messages from before we opened the log
67  m_buffering = false;
68  while (!m_msgs_before_open.empty()) {
69  const std::string& s = m_msgs_before_open.front();
70 
71  if (m_print_to_file) FileWriteStr(s, m_fileout);
72  if (m_print_to_console) fwrite(s.data(), 1, s.size(), stdout);
73  for (const auto& cb : m_print_callbacks) {
74  cb(s);
75  }
76 
77  m_msgs_before_open.pop_front();
78  }
79  if (m_print_to_console) fflush(stdout);
80 
81  return true;
82 }
83 
85 {
86  StdLockGuard scoped_lock(m_cs);
87  m_buffering = true;
88  if (m_fileout != nullptr) fclose(m_fileout);
89  m_fileout = nullptr;
90  m_print_callbacks.clear();
91 }
92 
94 {
95  m_categories |= flag;
96 }
97 
98 bool BCLog::Logger::EnableCategory(const std::string& str)
99 {
100  BCLog::LogFlags flag;
101  if (!GetLogCategory(flag, str)) return false;
102  EnableCategory(flag);
103  return true;
104 }
105 
107 {
108  m_categories &= ~flag;
109 }
110 
111 bool BCLog::Logger::DisableCategory(const std::string& str)
112 {
113  BCLog::LogFlags flag;
114  if (!GetLogCategory(flag, str)) return false;
115  DisableCategory(flag);
116  return true;
117 }
118 
120 {
121  return (m_categories.load(std::memory_order_relaxed) & category) != 0;
122 }
123 
125 {
126  return m_categories == BCLog::NONE;
127 }
128 
131  std::string category;
132 };
133 
135 {
136  {BCLog::NONE, "0"},
137  {BCLog::NONE, "none"},
138  {BCLog::NET, "net"},
139  {BCLog::TOR, "tor"},
140  {BCLog::MEMPOOL, "mempool"},
141  {BCLog::HTTP, "http"},
142  {BCLog::BENCH, "bench"},
143  {BCLog::ZMQ, "zmq"},
144  {BCLog::WALLETDB, "walletdb"},
145  {BCLog::RPC, "rpc"},
146  {BCLog::ESTIMATEFEE, "estimatefee"},
147  {BCLog::ADDRMAN, "addrman"},
148  {BCLog::SELECTCOINS, "selectcoins"},
149  {BCLog::REINDEX, "reindex"},
150  {BCLog::CMPCTBLOCK, "cmpctblock"},
151  {BCLog::RAND, "rand"},
152  {BCLog::PRUNE, "prune"},
153  {BCLog::PROXY, "proxy"},
154  {BCLog::MEMPOOLREJ, "mempoolrej"},
155  {BCLog::LIBEVENT, "libevent"},
156  {BCLog::COINDB, "coindb"},
157  {BCLog::QT, "qt"},
158  {BCLog::LEVELDB, "leveldb"},
159  {BCLog::VALIDATION, "validation"},
160  {BCLog::I2P, "i2p"},
161  {BCLog::IPC, "ipc"},
162  {BCLog::ALL, "1"},
163  {BCLog::ALL, "all"},
164 };
165 
166 bool GetLogCategory(BCLog::LogFlags& flag, const std::string& str)
167 {
168  if (str == "") {
169  flag = BCLog::ALL;
170  return true;
171  }
172  for (const CLogCategoryDesc& category_desc : LogCategories) {
173  if (category_desc.category == str) {
174  flag = category_desc.flag;
175  return true;
176  }
177  }
178  return false;
179 }
180 
181 std::vector<LogCategory> BCLog::Logger::LogCategoriesList() const
182 {
183  // Sort log categories by alphabetical order.
184  std::array<CLogCategoryDesc, std::size(LogCategories)> categories;
185  std::copy(std::begin(LogCategories), std::end(LogCategories), categories.begin());
186  std::sort(categories.begin(), categories.end(), [](auto a, auto b) { return a.category < b.category; });
187 
188  std::vector<LogCategory> ret;
189  for (const CLogCategoryDesc& category_desc : categories) {
190  if (category_desc.flag == BCLog::NONE || category_desc.flag == BCLog::ALL) continue;
191  LogCategory catActive;
192  catActive.category = category_desc.category;
193  catActive.active = WillLogCategory(category_desc.flag);
194  ret.push_back(catActive);
195  }
196  return ret;
197 }
198 
199 std::string BCLog::Logger::LogTimestampStr(const std::string& str)
200 {
201  std::string strStamped;
202 
203  if (!m_log_timestamps)
204  return str;
205 
206  if (m_started_new_line) {
207  int64_t nTimeMicros = GetTimeMicros();
208  strStamped = FormatISO8601DateTime(nTimeMicros/1000000);
209  if (m_log_time_micros) {
210  strStamped.pop_back();
211  strStamped += strprintf(".%06dZ", nTimeMicros%1000000);
212  }
213  std::chrono::seconds mocktime = GetMockTime();
214  if (mocktime > 0s) {
215  strStamped += " (mocktime: " + FormatISO8601DateTime(count_seconds(mocktime)) + ")";
216  }
217  strStamped += ' ' + str;
218  } else
219  strStamped = str;
220 
221  return strStamped;
222 }
223 
224 namespace BCLog {
232  std::string LogEscapeMessage(const std::string& str) {
233  std::string ret;
234  for (char ch_in : str) {
235  uint8_t ch = (uint8_t)ch_in;
236  if ((ch >= 32 || ch == '\n') && ch != '\x7f') {
237  ret += ch_in;
238  } else {
239  ret += strprintf("\\x%02x", ch);
240  }
241  }
242  return ret;
243  }
244 } // namespace BCLog
245 
246 void BCLog::Logger::LogPrintStr(const std::string& str, const std::string& logging_function, const std::string& source_file, const int source_line)
247 {
248  StdLockGuard scoped_lock(m_cs);
249  std::string str_prefixed = LogEscapeMessage(str);
250 
251  if (m_log_sourcelocations && m_started_new_line) {
252  str_prefixed.insert(0, "[" + RemovePrefix(source_file, "./") + ":" + ToString(source_line) + "] [" + logging_function + "] ");
253  }
254 
255  if (m_log_threadnames && m_started_new_line) {
256  str_prefixed.insert(0, "[" + util::ThreadGetInternalName() + "] ");
257  }
258 
259  str_prefixed = LogTimestampStr(str_prefixed);
260 
261  m_started_new_line = !str.empty() && str[str.size()-1] == '\n';
262 
263  if (m_buffering) {
264  // buffer if we haven't started logging yet
265  m_msgs_before_open.push_back(str_prefixed);
266  return;
267  }
268 
269  if (m_print_to_console) {
270  // print to console
271  fwrite(str_prefixed.data(), 1, str_prefixed.size(), stdout);
272  fflush(stdout);
273  }
274  for (const auto& cb : m_print_callbacks) {
275  cb(str_prefixed);
276  }
277  if (m_print_to_file) {
278  assert(m_fileout != nullptr);
279 
280  // reopen the log file, if requested
281  if (m_reopen_file) {
282  m_reopen_file = false;
283  FILE* new_fileout = fsbridge::fopen(m_file_path, "a");
284  if (new_fileout) {
285  setbuf(new_fileout, nullptr); // unbuffered
286  fclose(m_fileout);
287  m_fileout = new_fileout;
288  }
289  }
290  FileWriteStr(str_prefixed, m_fileout);
291  }
292 }
293 
295 {
296  // Amount of debug.log to save at end when shrinking (must fit in memory)
297  constexpr size_t RECENT_DEBUG_HISTORY_SIZE = 10 * 1000000;
298 
299  assert(!m_file_path.empty());
300 
301  // Scroll debug.log if it's getting too big
302  FILE* file = fsbridge::fopen(m_file_path, "r");
303 
304  // Special files (e.g. device nodes) may not have a size.
305  size_t log_size = 0;
306  try {
307  log_size = fs::file_size(m_file_path);
308  } catch (const fs::filesystem_error&) {}
309 
310  // If debug.log file is more than 10% bigger the RECENT_DEBUG_HISTORY_SIZE
311  // trim it down by saving only the last RECENT_DEBUG_HISTORY_SIZE bytes
312  if (file && log_size > 11 * (RECENT_DEBUG_HISTORY_SIZE / 10))
313  {
314  // Restart the file with some of the end
315  std::vector<char> vch(RECENT_DEBUG_HISTORY_SIZE, 0);
316  if (fseek(file, -((long)vch.size()), SEEK_END)) {
317  LogPrintf("Failed to shrink debug log file: fseek(...) failed\n");
318  fclose(file);
319  return;
320  }
321  int nBytes = fread(vch.data(), 1, vch.size(), file);
322  fclose(file);
323 
324  file = fsbridge::fopen(m_file_path, "w");
325  if (file)
326  {
327  fwrite(vch.data(), 1, nBytes, file);
328  fclose(file);
329  }
330  }
331  else if (file != nullptr)
332  fclose(file);
333 }
BCLog::LogFlags
LogFlags
Definition: logging.h:36
fLogIPs
bool fLogIPs
Definition: logging.cpp:38
BCLog::LogEscapeMessage
std::string LogEscapeMessage(const std::string &str)
Belts and suspenders: make sure outgoing log messages don't contain potentially suspicious characters...
Definition: logging.cpp:232
BCLog::Logger::m_print_to_file
bool m_print_to_file
Definition: logging.h:91
ToString
std::string ToString(const T &t)
Locale-independent version of std::to_string.
Definition: string.h:79
BCLog::IPC
@ IPC
Definition: logging.h:61
CLogCategoryDesc
Definition: logging.cpp:129
BCLog::ZMQ
@ ZMQ
Definition: logging.h:43
BCLog::I2P
@ I2P
Definition: logging.h:60
BCLog::HTTP
@ HTTP
Definition: logging.h:41
LogCategory::active
bool active
Definition: logging.h:32
FileWriteStr
static int FileWriteStr(const std::string &str, FILE *fp)
Definition: logging.cpp:40
BCLog::Logger::WillLogCategory
bool WillLogCategory(LogFlags category) const
Definition: logging.cpp:119
fsbridge::fopen
FILE * fopen(const fs::path &p, const char *mode)
Definition: fs.cpp:24
BCLog::Logger::StartLogging
bool StartLogging()
Start logging (and flush all buffered messages)
Definition: logging.cpp:45
string.h
GetMockTime
std::chrono::seconds GetMockTime()
For testing.
Definition: time.cpp:112
GetLogCategory
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:166
DEFAULT_LOGIPS
static const bool DEFAULT_LOGIPS
Definition: logging.h:22
LogCategory::category
std::string category
Definition: logging.h:31
BCLog::BENCH
@ BENCH
Definition: logging.h:42
FormatISO8601DateTime
std::string FormatISO8601DateTime(int64_t nTime)
ISO 8601 formatting is preferred.
Definition: time.cpp:132
BCLog::ESTIMATEFEE
@ ESTIMATEFEE
Definition: logging.h:46
BCLog::Logger::LogCategoriesList
std::vector< LogCategory > LogCategoriesList() const
Returns a vector of the log categories in alphabetical order.
Definition: logging.cpp:181
BCLog::PROXY
@ PROXY
Definition: logging.h:53
BCLog::PRUNE
@ PRUNE
Definition: logging.h:52
BCLog::Logger::DisconnectTestLogger
void DisconnectTestLogger()
Only for testing.
Definition: logging.cpp:84
BCLog::MEMPOOLREJ
@ MEMPOOLREJ
Definition: logging.h:54
BCLog::Logger::m_cs
StdMutex m_cs
Definition: logging.h:68
BCLog::RPC
@ RPC
Definition: logging.h:45
StdLockGuard
Definition: threadsafety.h:70
CLogCategoryDesc::category
std::string category
Definition: logging.cpp:131
BCLog::WALLETDB
@ WALLETDB
Definition: logging.h:44
BCLog::LEVELDB
@ LEVELDB
Definition: logging.h:58
BCLog::Logger::ShrinkDebugFile
void ShrinkDebugFile()
Definition: logging.cpp:294
util::ThreadGetInternalName
const std::string & ThreadGetInternalName()
Get the thread's internal (in-memory) name; used e.g.
Definition: threadnames.cpp:53
BCLog::LIBEVENT
@ LIBEVENT
Definition: logging.h:55
BCLog::Logger::LogTimestampStr
std::string LogTimestampStr(const std::string &str)
Definition: logging.cpp:199
time.h
LogCategory
Definition: logging.h:30
LogPrintf
#define LogPrintf(...)
Definition: logging.h:184
BCLog::Logger::EnableCategory
void EnableCategory(LogFlags flag)
Definition: logging.cpp:93
BCLog::TOR
@ TOR
Definition: logging.h:39
BCLog::REINDEX
@ REINDEX
Definition: logging.h:49
BCLog::QT
@ QT
Definition: logging.h:57
BCLog::ALL
@ ALL
Definition: logging.h:62
BCLog::VALIDATION
@ VALIDATION
Definition: logging.h:59
RemovePrefix
std::string RemovePrefix(const std::string &str, const std::string &prefix)
Definition: string.h:28
BCLog::Logger::m_file_path
fs::path m_file_path
Definition: logging.h:98
BCLog::RAND
@ RAND
Definition: logging.h:51
strprintf
#define strprintf
Format arguments and return the string or write to given std::ostream (see tinyformat::format doc for...
Definition: tinyformat.h:1164
BCLog::COINDB
@ COINDB
Definition: logging.h:56
BCLog::Logger::DefaultShrinkDebugFile
bool DefaultShrinkDebugFile() const
Definition: logging.cpp:124
BCLog
Definition: timer.h:17
BCLog::MEMPOOL
@ MEMPOOL
Definition: logging.h:40
BCLog::Logger::m_print_to_console
bool m_print_to_console
Definition: logging.h:90
BCLog::Logger
Definition: logging.h:65
logging.h
LogInstance
BCLog::Logger & LogInstance()
Definition: logging.cpp:17
count_seconds
constexpr int64_t count_seconds(std::chrono::seconds t)
Helper to count the seconds of a duration.
Definition: time.h:29
DEFAULT_DEBUGLOGFILE
const char *const DEFAULT_DEBUGLOGFILE
Definition: logging.cpp:15
BCLog::SELECTCOINS
@ SELECTCOINS
Definition: logging.h:48
assert
assert(s1.IsAddrV1Compatible())
LogCategories
const CLogCategoryDesc LogCategories[]
Definition: logging.cpp:134
BCLog::ADDRMAN
@ ADDRMAN
Definition: logging.h:47
GetTimeMicros
int64_t GetTimeMicros()
Returns the system time (not mockable)
Definition: time.cpp:122
BCLog::Logger::DisableCategory
void DisableCategory(LogFlags flag)
Definition: logging.cpp:106
BCLog::NET
@ NET
Definition: logging.h:38
threadnames.h
BCLog::CMPCTBLOCK
@ CMPCTBLOCK
Definition: logging.h:50
CLogCategoryDesc::flag
BCLog::LogFlags flag
Definition: logging.cpp:130
BCLog::NONE
@ NONE
Definition: logging.h:37
BCLog::Logger::LogPrintStr
void LogPrintStr(const std::string &str, const std::string &logging_function, const std::string &source_file, const int source_line)
Send a string to the log output.
Definition: logging.cpp:246