Bitcoin ABC  0.24.7
P2P Digital Currency
logging.cpp
Go to the documentation of this file.
1 // Copyright (c) 2009-2010 Satoshi Nakamoto
2 // Copyright (c) 2009-2016 The Bitcoin Core developers
3 // Copyright (c) 2017-2019 The Bitcoin developers
4 // Distributed under the MIT software license, see the accompanying
5 // file COPYING or http://www.opensource.org/licenses/mit-license.php.
6 
7 #include <logging.h>
8 
9 #include <util/threadnames.h>
10 #include <util/time.h>
11 
13 const char *const DEFAULT_DEBUGLOGFILE = "debug.log";
14 
31  static BCLog::Logger *g_logger{new BCLog::Logger()};
32  return *g_logger;
33 }
34 
35 static int FileWriteStr(const std::string &str, FILE *fp) {
36  return fwrite(str.data(), 1, str.size(), fp);
37 }
38 
40  StdLockGuard scoped_lock(m_cs);
41 
42  assert(m_buffering);
43  assert(m_fileout == nullptr);
44 
45  if (m_print_to_file) {
46  assert(!m_file_path.empty());
47  m_fileout = fsbridge::fopen(m_file_path, "a");
48  if (!m_fileout) {
49  return false;
50  }
51 
52  // Unbuffered.
53  setbuf(m_fileout, nullptr);
54 
55  // Add newlines to the logfile to distinguish this execution from the
56  // last one.
57  FileWriteStr("\n\n\n\n\n", m_fileout);
58  }
59 
60  // Dump buffered messages from before we opened the log.
61  m_buffering = false;
62  while (!m_msgs_before_open.empty()) {
63  const std::string &s = m_msgs_before_open.front();
64 
65  if (m_print_to_file) {
66  FileWriteStr(s, m_fileout);
67  }
68  if (m_print_to_console) {
69  fwrite(s.data(), 1, s.size(), stdout);
70  }
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) {
78  fflush(stdout);
79  }
80 
81  return true;
82 }
83 
85  StdLockGuard scoped_lock(m_cs);
86  m_buffering = true;
87  if (m_fileout != nullptr) {
88  fclose(m_fileout);
89  }
90  m_fileout = nullptr;
91  m_print_callbacks.clear();
92 }
93 
96  std::string category;
97 };
98 
100  {BCLog::NONE, "0"},
101  {BCLog::NONE, "none"},
102  {BCLog::NET, "net"},
103  {BCLog::TOR, "tor"},
104  {BCLog::MEMPOOL, "mempool"},
105  {BCLog::HTTP, "http"},
106  {BCLog::BENCH, "bench"},
107  {BCLog::ZMQ, "zmq"},
108  {BCLog::WALLETDB, "walletdb"},
109  {BCLog::RPC, "rpc"},
110  {BCLog::ESTIMATEFEE, "estimatefee"},
111  {BCLog::ADDRMAN, "addrman"},
112  {BCLog::SELECTCOINS, "selectcoins"},
113  {BCLog::REINDEX, "reindex"},
114  {BCLog::CMPCTBLOCK, "cmpctblock"},
115  {BCLog::RAND, "rand"},
116  {BCLog::PRUNE, "prune"},
117  {BCLog::PROXY, "proxy"},
118  {BCLog::MEMPOOLREJ, "mempoolrej"},
119  {BCLog::LIBEVENT, "libevent"},
120  {BCLog::COINDB, "coindb"},
121  {BCLog::QT, "qt"},
122  {BCLog::LEVELDB, "leveldb"},
123  {BCLog::VALIDATION, "validation"},
124  {BCLog::AVALANCHE, "avalanche"},
125  {BCLog::ALL, "1"},
126  {BCLog::ALL, "all"},
127 };
128 
129 bool GetLogCategory(BCLog::LogFlags &flag, const std::string &str) {
130  if (str == "") {
131  flag = BCLog::ALL;
132  return true;
133  }
134  for (const CLogCategoryDesc &category_desc : LogCategories) {
135  if (category_desc.category == str) {
136  flag = category_desc.flag;
137  return true;
138  }
139  }
140  return false;
141 }
142 
143 std::vector<LogCategory> BCLog::Logger::LogCategoriesList() {
144  std::vector<LogCategory> ret;
145  for (const CLogCategoryDesc &category_desc : LogCategories) {
146  // Omit the special cases.
147  if (category_desc.flag != BCLog::NONE &&
148  category_desc.flag != BCLog::ALL) {
149  LogCategory catActive;
150  catActive.category = category_desc.category;
151  catActive.active = WillLogCategory(category_desc.flag);
152  ret.push_back(catActive);
153  }
154  }
155  return ret;
156 }
157 
159  if (m_fileout) {
160  fclose(m_fileout);
161  }
162 }
163 
164 std::string BCLog::Logger::LogTimestampStr(const std::string &str) {
165  std::string strStamped;
166 
167  if (!m_log_timestamps) {
168  return str;
169  }
170 
171  if (m_started_new_line) {
172  int64_t nTimeMicros = GetTimeMicros();
173  strStamped = FormatISO8601DateTime(nTimeMicros / 1000000);
174  if (m_log_time_micros) {
175  strStamped.pop_back();
176  strStamped += strprintf(".%06dZ", nTimeMicros % 1000000);
177  }
178  int64_t mocktime = GetMockTime();
179  if (mocktime) {
180  strStamped +=
181  " (mocktime: " + FormatISO8601DateTime(mocktime) + ")";
182  }
183  strStamped += ' ' + str;
184  } else {
185  strStamped = str;
186  }
187 
188  return strStamped;
189 }
190 
191 namespace BCLog {
199 std::string LogEscapeMessage(const std::string &str) {
200  std::string ret;
201  for (char ch_in : str) {
202  uint8_t ch = (uint8_t)ch_in;
203  if ((ch >= 32 || ch == '\n') && ch != '\x7f') {
204  ret += ch_in;
205  } else {
206  ret += strprintf("\\x%02x", ch);
207  }
208  }
209  return ret;
210 }
211 } // namespace BCLog
212 
213 void BCLog::Logger::LogPrintStr(const std::string &str) {
214  StdLockGuard scoped_lock(m_cs);
215  std::string str_prefixed = LogEscapeMessage(str);
216 
217  if (m_log_threadnames && m_started_new_line) {
218  str_prefixed.insert(0, "[" + util::ThreadGetInternalName() + "] ");
219  }
220 
221  str_prefixed = LogTimestampStr(str_prefixed);
222 
223  m_started_new_line = !str.empty() && str[str.size() - 1] == '\n';
224 
225  if (m_buffering) {
226  // buffer if we haven't started logging yet
227  m_msgs_before_open.push_back(str_prefixed);
228  return;
229  }
230 
231  if (m_print_to_console) {
232  // Print to console.
233  fwrite(str_prefixed.data(), 1, str_prefixed.size(), stdout);
234  fflush(stdout);
235  }
236  for (const auto &cb : m_print_callbacks) {
237  cb(str_prefixed);
238  }
239  if (m_print_to_file) {
240  assert(m_fileout != nullptr);
241 
242  // Reopen the log file, if requested.
243  if (m_reopen_file) {
244  m_reopen_file = false;
245  FILE *new_fileout = fsbridge::fopen(m_file_path, "a");
246  if (new_fileout) {
247  // unbuffered.
248  setbuf(m_fileout, nullptr);
249  fclose(m_fileout);
250  m_fileout = new_fileout;
251  }
252  }
253  FileWriteStr(str_prefixed, m_fileout);
254  }
255 }
256 
258  // Amount of debug.log to save at end when shrinking (must fit in memory)
259  constexpr size_t RECENT_DEBUG_HISTORY_SIZE = 10 * 1000000;
260 
261  assert(!m_file_path.empty());
262 
263  // Scroll debug.log if it's getting too big.
264  FILE *file = fsbridge::fopen(m_file_path, "r");
265 
266  // Special files (e.g. device nodes) may not have a size.
267  size_t log_size = 0;
268  try {
269  log_size = fs::file_size(m_file_path);
270  } catch (const fs::filesystem_error &) {
271  }
272 
273  // If debug.log file is more than 10% bigger the RECENT_DEBUG_HISTORY_SIZE
274  // trim it down by saving only the last RECENT_DEBUG_HISTORY_SIZE bytes.
275  if (file && log_size > 11 * (RECENT_DEBUG_HISTORY_SIZE / 10)) {
276  // Restart the file with some of the end.
277  std::vector<char> vch(RECENT_DEBUG_HISTORY_SIZE, 0);
278  if (fseek(file, -((long)vch.size()), SEEK_END)) {
279  LogPrintf("Failed to shrink debug log file: fseek(...) failed\n");
280  fclose(file);
281  return;
282  }
283  int nBytes = fread(vch.data(), 1, vch.size(), file);
284  fclose(file);
285 
286  file = fsbridge::fopen(m_file_path, "w");
287  if (file) {
288  fwrite(vch.data(), 1, nBytes, file);
289  fclose(file);
290  }
291  } else if (file != nullptr) {
292  fclose(file);
293  }
294 }
295 
297  m_categories |= category;
298 }
299 
300 bool BCLog::Logger::EnableCategory(const std::string &str) {
301  BCLog::LogFlags flag;
302  if (!GetLogCategory(flag, str)) {
303  return false;
304  }
305  EnableCategory(flag);
306  return true;
307 }
308 
310  m_categories &= ~category;
311 }
312 
313 bool BCLog::Logger::DisableCategory(const std::string &str) {
314  BCLog::LogFlags flag;
315  if (!GetLogCategory(flag, str)) {
316  return false;
317  }
318  DisableCategory(flag);
319  return true;
320 }
321 
323  // ALL is not meant to be used as a logging category, but only as a mask
324  // representing all categories.
325  if (category == BCLog::NONE || category == BCLog::ALL) {
326  LogPrintf("Error trying to log using a category mask instead of an "
327  "explicit category.\n");
328  return true;
329  }
330 
331  return (m_categories.load(std::memory_order_relaxed) & category) != 0;
332 }
333 
335  return m_categories != BCLog::NONE;
336 }
BCLog::LogFlags
LogFlags
Definition: logging.h:36
fLogIPs
bool fLogIPs
Definition: logging.cpp:12
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:199
BCLog::Logger::m_print_to_file
bool m_print_to_file
Definition: logging.h:94
BCLog::Logger::LogPrintStr
void LogPrintStr(const std::string &str)
Send a string to the log output.
Definition: logging.cpp:213
CLogCategoryDesc
Definition: logging.cpp:94
BCLog::ZMQ
@ ZMQ
Definition: logging.h:43
BCLog::HTTP
@ HTTP
Definition: logging.h:41
LogCategory::active
bool active
Definition: logging.h:31
FileWriteStr
static int FileWriteStr(const std::string &str, FILE *fp)
Definition: logging.cpp:35
BCLog::Logger::WillLogCategory
bool WillLogCategory(LogFlags category) const
Return true if log accepts specified category.
Definition: logging.cpp:322
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:39
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:129
DEFAULT_LOGIPS
static const bool DEFAULT_LOGIPS
Definition: logging.h:22
LogCategory::category
std::string category
Definition: logging.h:30
BCLog::BENCH
@ BENCH
Definition: logging.h:42
BCLog::Logger::~Logger
~Logger()
Definition: logging.cpp:158
FormatISO8601DateTime
std::string FormatISO8601DateTime(int64_t nTime)
ISO 8601 formatting is preferred.
Definition: time.cpp:79
BCLog::ESTIMATEFEE
@ ESTIMATEFEE
Definition: logging.h:46
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
GetMockTime
int64_t GetMockTime()
For testing.
Definition: time.cpp:55
BCLog::Logger::m_cs
StdMutex m_cs
Definition: logging.h:68
BCLog::RPC
@ RPC
Definition: logging.h:45
StdLockGuard
Definition: threadsafety.h:77
CLogCategoryDesc::category
std::string category
Definition: logging.cpp:96
BCLog::WALLETDB
@ WALLETDB
Definition: logging.h:44
BCLog::Logger::LogCategoriesList
std::vector< LogCategory > LogCategoriesList()
Returns a vector of the log categories.
Definition: logging.cpp:143
BCLog::LEVELDB
@ LEVELDB
Definition: logging.h:58
BCLog::Logger::ShrinkDebugFile
void ShrinkDebugFile()
Definition: logging.cpp:257
util::ThreadGetInternalName
const std::string & ThreadGetInternalName()
Get the thread's internal (in-memory) name; used e.g.
Definition: threadnames.cpp:39
BCLog::LIBEVENT
@ LIBEVENT
Definition: logging.h:55
BCLog::Logger::LogTimestampStr
std::string LogTimestampStr(const std::string &str)
Definition: logging.cpp:164
time.h
LogCategory
Definition: logging.h:29
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
BCLog::Logger::EnableCategory
void EnableCategory(LogFlags category)
Definition: logging.cpp:296
BCLog::Logger::m_file_path
fs::path m_file_path
Definition: logging.h:100
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:1201
BCLog::COINDB
@ COINDB
Definition: logging.h:56
BCLog::Logger::DefaultShrinkDebugFile
bool DefaultShrinkDebugFile() const
Default for whether ShrinkDebugFile should be run.
Definition: logging.cpp:334
BCLog
Definition: timer.h:16
BCLog::MEMPOOL
@ MEMPOOL
Definition: logging.h:40
BCLog::AVALANCHE
@ AVALANCHE
Definition: logging.h:60
BCLog::Logger::m_print_to_console
bool m_print_to_console
Definition: logging.h:93
BCLog::Logger
Definition: logging.h:64
logging.h
LogInstance
BCLog::Logger & LogInstance()
Definition: logging.cpp:15
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:99
BCLog::ADDRMAN
@ ADDRMAN
Definition: logging.h:47
GetTimeMicros
int64_t GetTimeMicros()
Returns the system time (not mockable)
Definition: time.cpp:67
BCLog::NET
@ NET
Definition: logging.h:38
threadnames.h
BCLog::CMPCTBLOCK
@ CMPCTBLOCK
Definition: logging.h:50
LogPrintf
static void LogPrintf(const char *fmt, const Args &... args)
Definition: logging.h:175
CLogCategoryDesc::flag
BCLog::LogFlags flag
Definition: logging.cpp:95
BCLog::Logger::DisableCategory
void DisableCategory(LogFlags category)
Definition: logging.cpp:309
BCLog::NONE
@ NONE
Definition: logging.h:37