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