Bitcoin Core  28.1.0
P2P Digital Currency
logging.h
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 #ifndef BITCOIN_LOGGING_H
7 #define BITCOIN_LOGGING_H
8 
9 #include <threadsafety.h>
10 #include <tinyformat.h>
11 #include <util/fs.h>
12 #include <util/string.h>
13 #include <util/time.h>
14 
15 #include <atomic>
16 #include <cstdint>
17 #include <functional>
18 #include <list>
19 #include <mutex>
20 #include <string>
21 #include <unordered_map>
22 #include <vector>
23 
24 static const bool DEFAULT_LOGTIMEMICROS = false;
25 static const bool DEFAULT_LOGIPS = false;
26 static const bool DEFAULT_LOGTIMESTAMPS = true;
27 static const bool DEFAULT_LOGTHREADNAMES = false;
28 static const bool DEFAULT_LOGSOURCELOCATIONS = false;
29 static constexpr bool DEFAULT_LOGLEVELALWAYS = false;
30 extern const char * const DEFAULT_DEBUGLOGFILE;
31 
32 extern bool fLogIPs;
33 
34 struct LogCategory {
35  std::string category;
36  bool active;
37 };
38 
39 namespace BCLog {
40  enum LogFlags : uint32_t {
41  NONE = 0,
42  NET = (1 << 0),
43  TOR = (1 << 1),
44  MEMPOOL = (1 << 2),
45  HTTP = (1 << 3),
46  BENCH = (1 << 4),
47  ZMQ = (1 << 5),
48  WALLETDB = (1 << 6),
49  RPC = (1 << 7),
50  ESTIMATEFEE = (1 << 8),
51  ADDRMAN = (1 << 9),
52  SELECTCOINS = (1 << 10),
53  REINDEX = (1 << 11),
54  CMPCTBLOCK = (1 << 12),
55  RAND = (1 << 13),
56  PRUNE = (1 << 14),
57  PROXY = (1 << 15),
58  MEMPOOLREJ = (1 << 16),
59  LIBEVENT = (1 << 17),
60  COINDB = (1 << 18),
61  QT = (1 << 19),
62  LEVELDB = (1 << 20),
63  VALIDATION = (1 << 21),
64  I2P = (1 << 22),
65  IPC = (1 << 23),
66 #ifdef DEBUG_LOCKCONTENTION
67  LOCK = (1 << 24),
68 #endif
69  BLOCKSTORAGE = (1 << 25),
70  TXRECONCILIATION = (1 << 26),
71  SCAN = (1 << 27),
72  TXPACKAGES = (1 << 28),
73  ALL = ~(uint32_t)0,
74  };
75  enum class Level {
76  Trace = 0, // High-volume or detailed logging for development/debugging
77  Debug, // Reasonably noisy logging, but still usable in production
78  Info, // Default
79  Warning,
80  Error,
81  };
83  constexpr size_t DEFAULT_MAX_LOG_BUFFER{1'000'000}; // buffer up to 1MB of log data prior to StartLogging
84 
85  class Logger
86  {
87  public:
88  struct BufferedLog {
89  SystemClock::time_point now;
90  std::chrono::seconds mocktime;
95  };
96 
97  private:
98  mutable StdMutex m_cs; // Can not use Mutex from sync.h because in debug mode it would cause a deadlock when a potential deadlock was detected
99 
100  FILE* m_fileout GUARDED_BY(m_cs) = nullptr;
101  std::list<BufferedLog> m_msgs_before_open GUARDED_BY(m_cs);
102  bool m_buffering GUARDED_BY(m_cs) = true;
103  size_t m_max_buffer_memusage GUARDED_BY(m_cs){DEFAULT_MAX_LOG_BUFFER};
104  size_t m_cur_buffer_memusage GUARDED_BY(m_cs){0};
105  size_t m_buffer_lines_discarded GUARDED_BY(m_cs){0};
106 
112  std::atomic_bool m_started_new_line{true};
113 
115  std::unordered_map<LogFlags, Level> m_category_log_levels GUARDED_BY(m_cs);
116 
119  std::atomic<Level> m_log_level{DEFAULT_LOG_LEVEL};
120 
122  std::atomic<uint32_t> m_categories{BCLog::NONE};
123 
124  void FormatLogStrInPlace(std::string& str, LogFlags category, Level level, std::string_view source_file, int source_line, std::string_view logging_function, std::string_view threadname, SystemClock::time_point now, std::chrono::seconds mocktime) const;
125 
126  std::string LogTimestampStr(SystemClock::time_point now, std::chrono::seconds mocktime) const;
127 
129  std::list<std::function<void(const std::string&)>> m_print_callbacks GUARDED_BY(m_cs) {};
130 
132  void LogPrintStr_(std::string_view str, std::string_view logging_function, std::string_view source_file, int source_line, BCLog::LogFlags category, BCLog::Level level)
134 
135  std::string GetLogPrefix(LogFlags category, Level level) const;
136 
137  public:
138  bool m_print_to_console = false;
139  bool m_print_to_file = false;
140 
146 
148  std::atomic<bool> m_reopen_file{false};
149 
151  void LogPrintStr(std::string_view str, std::string_view logging_function, std::string_view source_file, int source_line, BCLog::LogFlags category, BCLog::Level level)
153 
156  {
157  StdLockGuard scoped_lock(m_cs);
158  return m_buffering || m_print_to_console || m_print_to_file || !m_print_callbacks.empty();
159  }
160 
162  std::list<std::function<void(const std::string&)>>::iterator PushBackCallback(std::function<void(const std::string&)> fun) EXCLUSIVE_LOCKS_REQUIRED(!m_cs)
163  {
164  StdLockGuard scoped_lock(m_cs);
165  m_print_callbacks.push_back(std::move(fun));
166  return --m_print_callbacks.end();
167  }
168 
170  void DeleteCallback(std::list<std::function<void(const std::string&)>>::iterator it) EXCLUSIVE_LOCKS_REQUIRED(!m_cs)
171  {
172  StdLockGuard scoped_lock(m_cs);
173  m_print_callbacks.erase(it);
174  }
175 
180 
188 
189  void ShrinkDebugFile();
190 
192  {
193  StdLockGuard scoped_lock(m_cs);
194  return m_category_log_levels;
195  }
196  void SetCategoryLogLevel(const std::unordered_map<LogFlags, Level>& levels) EXCLUSIVE_LOCKS_REQUIRED(!m_cs)
197  {
198  StdLockGuard scoped_lock(m_cs);
199  m_category_log_levels = levels;
200  }
201  bool SetCategoryLogLevel(std::string_view category_str, std::string_view level_str) EXCLUSIVE_LOCKS_REQUIRED(!m_cs);
202 
203  Level LogLevel() const { return m_log_level.load(); }
204  void SetLogLevel(Level level) { m_log_level = level; }
205  bool SetLogLevel(std::string_view level);
206 
207  uint32_t GetCategoryMask() const { return m_categories.load(); }
208 
209  void EnableCategory(LogFlags flag);
210  bool EnableCategory(std::string_view str);
211  void DisableCategory(LogFlags flag);
212  bool DisableCategory(std::string_view str);
213 
214  bool WillLogCategory(LogFlags category) const;
215  bool WillLogCategoryLevel(LogFlags category, Level level) const EXCLUSIVE_LOCKS_REQUIRED(!m_cs);
216 
218  std::vector<LogCategory> LogCategoriesList() const;
220  std::string LogCategoriesString() const
221  {
222  return util::Join(LogCategoriesList(), ", ", [&](const LogCategory& i) { return i.category; });
223  };
224 
226  std::string LogLevelsString() const;
227 
229  static std::string LogLevelToStr(BCLog::Level level);
230 
231  bool DefaultShrinkDebugFile() const;
232  };
233 
234 } // namespace BCLog
235 
237 
239 static inline bool LogAcceptCategory(BCLog::LogFlags category, BCLog::Level level)
240 {
241  return LogInstance().WillLogCategoryLevel(category, level);
242 }
243 
245 bool GetLogCategory(BCLog::LogFlags& flag, std::string_view str);
246 
247 // Be conservative when using functions that
248 // unconditionally log to debug.log! It should not be the case that an inbound
249 // peer can fill up a user's disk with debug.log entries.
250 
251 template <typename... Args>
252 static inline void LogPrintf_(std::string_view logging_function, std::string_view source_file, const int source_line, const BCLog::LogFlags flag, const BCLog::Level level, const char* fmt, const Args&... args)
253 {
254  if (LogInstance().Enabled()) {
255  std::string log_msg;
256  try {
257  log_msg = tfm::format(fmt, args...);
258  } catch (tinyformat::format_error& fmterr) {
259  /* Original format string will have newline so don't add one here */
260  log_msg = "Error \"" + std::string(fmterr.what()) + "\" while formatting log message: " + fmt;
261  }
262  LogInstance().LogPrintStr(log_msg, logging_function, source_file, source_line, flag, level);
263  }
264 }
265 
266 #define LogPrintLevel_(category, level, ...) LogPrintf_(__func__, __FILE__, __LINE__, category, level, __VA_ARGS__)
267 
268 // Log unconditionally.
269 #define LogInfo(...) LogPrintLevel_(BCLog::LogFlags::ALL, BCLog::Level::Info, __VA_ARGS__)
270 #define LogWarning(...) LogPrintLevel_(BCLog::LogFlags::ALL, BCLog::Level::Warning, __VA_ARGS__)
271 #define LogError(...) LogPrintLevel_(BCLog::LogFlags::ALL, BCLog::Level::Error, __VA_ARGS__)
272 
273 // Deprecated unconditional logging.
274 #define LogPrintf(...) LogInfo(__VA_ARGS__)
275 #define LogPrintfCategory(category, ...) LogPrintLevel_(category, BCLog::Level::Info, __VA_ARGS__)
276 
277 // Use a macro instead of a function for conditional logging to prevent
278 // evaluating arguments when logging for the category is not enabled.
279 
280 // Log conditionally, prefixing the output with the passed category name and severity level.
281 #define LogPrintLevel(category, level, ...) \
282  do { \
283  if (LogAcceptCategory((category), (level))) { \
284  LogPrintLevel_(category, level, __VA_ARGS__); \
285  } \
286  } while (0)
287 
288 // Log conditionally, prefixing the output with the passed category name.
289 #define LogDebug(category, ...) LogPrintLevel(category, BCLog::Level::Debug, __VA_ARGS__)
290 #define LogTrace(category, ...) LogPrintLevel(category, BCLog::Level::Trace, __VA_ARGS__)
291 
292 // Deprecated conditional logging
293 #define LogPrint(category, ...) LogDebug(category, __VA_ARGS__)
294 
295 #endif // BITCOIN_LOGGING_H
void EnableCategory(LogFlags flag)
Definition: logging.cpp:121
void DisableLogging() EXCLUSIVE_LOCKS_REQUIRED(!m_cs)
Disable logging This offers a slight speedup and slightly smaller memory usage compared to leaving th...
Definition: logging.cpp:109
StdMutex m_cs
Definition: logging.h:98
size_t m_buffer_lines_discarded GUARDED_BY(m_cs)
Definition: logging.h:105
FILE *m_fileout GUARDED_BY(m_cs)
std::unordered_map< LogFlags, Level > CategoryLevels() const EXCLUSIVE_LOCKS_REQUIRED(!m_cs)
Definition: logging.h:191
fs::path m_file_path
Definition: logging.h:147
Definition: timer.h:19
std::string threadname
Definition: logging.h:91
Level LogLevel() const
Definition: logging.h:203
bool fLogIPs
Definition: logging.cpp:44
static void LogPrintf_(std::string_view logging_function, std::string_view source_file, const int source_line, const BCLog::LogFlags flag, const BCLog::Level level, const char *fmt, const Args &... args)
Definition: logging.h:252
static const bool DEFAULT_LOGTHREADNAMES
Definition: logging.h:27
std::chrono::seconds mocktime
Definition: logging.h:90
static const bool DEFAULT_LOGTIMEMICROS
Definition: logging.h:24
std::atomic< bool > m_reopen_file
Definition: logging.h:148
bool m_print_to_console
Definition: logging.h:138
SystemClock::time_point now
Definition: logging.h:89
std::atomic< Level > m_log_level
If there is no category-specific log level, all logs with a severity level lower than m_log_level wil...
Definition: logging.h:119
BCLog::Logger & LogInstance()
Definition: logging.cpp:23
bool m_log_sourcelocations
Definition: logging.h:144
bool m_print_to_file
Definition: logging.h:139
constexpr auto DEFAULT_LOG_LEVEL
Definition: logging.h:82
bool Enabled() const EXCLUSIVE_LOCKS_REQUIRED(!m_cs)
Returns whether logs will be written to any output.
Definition: logging.h:155
static constexpr bool DEFAULT_LOGLEVELALWAYS
Definition: logging.h:29
ArgsManager & args
Definition: bitcoind.cpp:270
std::string category
Definition: logging.h:35
bool m_log_threadnames
Definition: logging.h:143
bool m_always_print_category_level
Definition: logging.h:145
bool m_log_time_micros
Definition: logging.h:142
std::string LogTimestampStr(SystemClock::time_point now, std::chrono::seconds mocktime) const
Definition: logging.cpp:296
#define LOCK(cs)
Definition: sync.h:257
void format(std::ostream &out, const char *fmt, const Args &... args)
Format list of arguments to the stream according to given format string.
Definition: tinyformat.h:1059
void FormatLogStrInPlace(std::string &str, LogFlags category, Level level, std::string_view source_file, int source_line, std::string_view logging_function, std::string_view threadname, SystemClock::time_point now, std::chrono::seconds mocktime) const
Definition: logging.cpp:370
constexpr size_t DEFAULT_MAX_LOG_BUFFER
Definition: logging.h:83
uint32_t GetCategoryMask() const
Definition: logging.h:207
void DisableCategory(LogFlags flag)
Definition: logging.cpp:134
void SetCategoryLogLevel(const std::unordered_map< LogFlags, Level > &levels) EXCLUSIVE_LOCKS_REQUIRED(!m_cs)
Definition: logging.h:196
void SetLogLevel(Level level)
Definition: logging.h:204
bool WillLogCategory(LogFlags category) const
Definition: logging.cpp:147
void DeleteCallback(std::list< std::function< void(const std::string &)>>::iterator it) EXCLUSIVE_LOCKS_REQUIRED(!m_cs)
Delete a connection.
Definition: logging.h:170
std::atomic< uint32_t > m_categories
Log categories bitfield.
Definition: logging.h:122
Level
Definition: logging.h:75
std::string GetLogPrefix(LogFlags category, Level level) const
Definition: logging.cpp:339
void DisconnectTestLogger() EXCLUSIVE_LOCKS_REQUIRED(!m_cs)
Only for testing.
Definition: logging.cpp:95
void LogPrintStr_(std::string_view str, std::string_view logging_function, std::string_view source_file, int source_line, BCLog::LogFlags category, BCLog::Level level) EXCLUSIVE_LOCKS_REQUIRED(m_cs)
Send a string to the log output (internal)
Definition: logging.cpp:391
static std::string LogLevelToStr(BCLog::Level level)
Returns the string representation of a log level.
Definition: logging.cpp:230
#define EXCLUSIVE_LOCKS_REQUIRED(...)
Definition: threadsafety.h:49
void LogPrintStr(std::string_view str, std::string_view logging_function, std::string_view source_file, int source_line, BCLog::LogFlags category, BCLog::Level level) EXCLUSIVE_LOCKS_REQUIRED(!m_cs)
Send a string to the log output.
Definition: logging.cpp:385
std::list< std::function< void(const std::string &)> > m_print_callbacks GUARDED_BY(m_cs)
Slots that connect to the print signal.
Definition: logging.h:129
std::atomic_bool m_started_new_line
m_started_new_line is a state variable that will suppress printing of the timestamp when multiple cal...
Definition: logging.h:112
std::list< std::function< void(const std::string &)> >::iterator PushBackCallback(std::function< void(const std::string &)> fun) EXCLUSIVE_LOCKS_REQUIRED(!m_cs)
Connect a slot to the print signal and return the connection.
Definition: logging.h:162
std::string logging_function
Definition: logging.h:91
static const bool DEFAULT_LOGSOURCELOCATIONS
Definition: logging.h:28
std::string source_file
Definition: logging.h:91
bool active
Definition: logging.h:36
LogFlags
Definition: logging.h:40
bool StartLogging() EXCLUSIVE_LOCKS_REQUIRED(!m_cs)
Start logging (and flush all buffered messages)
Definition: logging.cpp:51
std::string LogLevelsString() const
Returns a string with all user-selectable log levels.
Definition: logging.cpp:290
std::vector< LogCategory > LogCategoriesList() const
Returns a vector of the log categories in alphabetical order.
Definition: logging.cpp:274
size_t m_cur_buffer_memusage GUARDED_BY(m_cs)
Definition: logging.h:104
static bool LogAcceptCategory(BCLog::LogFlags category, BCLog::Level level)
Return true if log accepts specified category, at the specified level.
Definition: logging.h:239
bool m_log_timestamps
Definition: logging.h:141
static const bool DEFAULT_LOGIPS
Definition: logging.h:25
size_t m_max_buffer_memusage GUARDED_BY(m_cs)
Definition: logging.h:103
bool WillLogCategoryLevel(LogFlags category, Level level) const EXCLUSIVE_LOCKS_REQUIRED(!m_cs)
Definition: logging.cpp:152
const char *const DEFAULT_DEBUGLOGFILE
Definition: logging.cpp:20
Path class wrapper to block calls to the fs::path(std::string) implicit constructor and the fs::path:...
Definition: fs.h:32
auto Join(const C &container, const S &separator, UnaryOp unary_op)
Join all container items.
Definition: string.h:115
static const bool DEFAULT_LOGTIMESTAMPS
Definition: logging.h:26
bool GetLogCategory(BCLog::LogFlags &flag, std::string_view str)
Return true if str parses as a log category and set the flag.
Definition: logging.cpp:216
std::string LogCategoriesString() const
Returns a string with the log categories in alphabetical order.
Definition: logging.h:220
void ShrinkDebugFile()
Definition: logging.cpp:468
bool DefaultShrinkDebugFile() const
Definition: logging.cpp:165