Bitcoin Core  24.99.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 <fs.h>
10 #include <threadsafety.h>
11 #include <tinyformat.h>
12 #include <util/string.h>
13 
14 #include <atomic>
15 #include <cstdint>
16 #include <functional>
17 #include <list>
18 #include <mutex>
19 #include <string>
20 #include <unordered_map>
21 #include <vector>
22 
23 static const bool DEFAULT_LOGTIMEMICROS = false;
24 static const bool DEFAULT_LOGIPS = false;
25 static const bool DEFAULT_LOGTIMESTAMPS = true;
26 static const bool DEFAULT_LOGTHREADNAMES = false;
27 static const bool DEFAULT_LOGSOURCELOCATIONS = false;
28 extern const char * const DEFAULT_DEBUGLOGFILE;
29 
30 extern bool fLogIPs;
31 
32 struct LogCategory {
33  std::string category;
34  bool active;
35 };
36 
37 namespace BCLog {
38  enum LogFlags : uint32_t {
39  NONE = 0,
40  NET = (1 << 0),
41  TOR = (1 << 1),
42  MEMPOOL = (1 << 2),
43  HTTP = (1 << 3),
44  BENCH = (1 << 4),
45  ZMQ = (1 << 5),
46  WALLETDB = (1 << 6),
47  RPC = (1 << 7),
48  ESTIMATEFEE = (1 << 8),
49  ADDRMAN = (1 << 9),
50  SELECTCOINS = (1 << 10),
51  REINDEX = (1 << 11),
52  CMPCTBLOCK = (1 << 12),
53  RAND = (1 << 13),
54  PRUNE = (1 << 14),
55  PROXY = (1 << 15),
56  MEMPOOLREJ = (1 << 16),
57  LIBEVENT = (1 << 17),
58  COINDB = (1 << 18),
59  QT = (1 << 19),
60  LEVELDB = (1 << 20),
61  VALIDATION = (1 << 21),
62  I2P = (1 << 22),
63  IPC = (1 << 23),
64 #ifdef DEBUG_LOCKCONTENTION
65  LOCK = (1 << 24),
66 #endif
67  UTIL = (1 << 25),
68  BLOCKSTORE = (1 << 26),
69  TXRECONCILIATION = (1 << 27),
70  SCAN = (1 << 28),
71  ALL = ~(uint32_t)0,
72  };
73  enum class Level {
74  Trace = 0, // High-volume or detailed logging for development/debugging
75  Debug, // Reasonably noisy logging, but still usable in production
76  Info, // Default
77  Warning,
78  Error,
79  None, // Internal use only
80  };
82 
83  class Logger
84  {
85  private:
86  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
87 
88  FILE* m_fileout GUARDED_BY(m_cs) = nullptr;
89  std::list<std::string> m_msgs_before_open GUARDED_BY(m_cs);
90  bool m_buffering GUARDED_BY(m_cs) = true;
91 
97  std::atomic_bool m_started_new_line{true};
98 
100  std::unordered_map<LogFlags, Level> m_category_log_levels GUARDED_BY(m_cs);
101 
104  std::atomic<Level> m_log_level{DEFAULT_LOG_LEVEL};
105 
107  std::atomic<uint32_t> m_categories{0};
108 
109  std::string LogTimestampStr(const std::string& str);
110 
112  std::list<std::function<void(const std::string&)>> m_print_callbacks GUARDED_BY(m_cs) {};
113 
114  public:
115  bool m_print_to_console = false;
116  bool m_print_to_file = false;
117 
122 
124  std::atomic<bool> m_reopen_file{false};
125 
127  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);
128 
130  bool Enabled() const
131  {
132  StdLockGuard scoped_lock(m_cs);
133  return m_buffering || m_print_to_console || m_print_to_file || !m_print_callbacks.empty();
134  }
135 
137  std::list<std::function<void(const std::string&)>>::iterator PushBackCallback(std::function<void(const std::string&)> fun)
138  {
139  StdLockGuard scoped_lock(m_cs);
140  m_print_callbacks.push_back(std::move(fun));
141  return --m_print_callbacks.end();
142  }
143 
145  void DeleteCallback(std::list<std::function<void(const std::string&)>>::iterator it)
146  {
147  StdLockGuard scoped_lock(m_cs);
148  m_print_callbacks.erase(it);
149  }
150 
152  bool StartLogging();
154  void DisconnectTestLogger();
155 
156  void ShrinkDebugFile();
157 
158  std::unordered_map<LogFlags, Level> CategoryLevels() const
159  {
160  StdLockGuard scoped_lock(m_cs);
161  return m_category_log_levels;
162  }
163  void SetCategoryLogLevel(const std::unordered_map<LogFlags, Level>& levels)
164  {
165  StdLockGuard scoped_lock(m_cs);
166  m_category_log_levels = levels;
167  }
168  bool SetCategoryLogLevel(const std::string& category_str, const std::string& level_str);
169 
170  Level LogLevel() const { return m_log_level.load(); }
171  void SetLogLevel(Level level) { m_log_level = level; }
172  bool SetLogLevel(const std::string& level);
173 
174  uint32_t GetCategoryMask() const { return m_categories.load(); }
175 
176  void EnableCategory(LogFlags flag);
177  bool EnableCategory(const std::string& str);
178  void DisableCategory(LogFlags flag);
179  bool DisableCategory(const std::string& str);
180 
181  bool WillLogCategory(LogFlags category) const;
182  bool WillLogCategoryLevel(LogFlags category, Level level) const;
183 
185  std::vector<LogCategory> LogCategoriesList() const;
187  std::string LogCategoriesString() const
188  {
189  return Join(LogCategoriesList(), ", ", [&](const LogCategory& i) { return i.category; });
190  };
191 
193  std::string LogLevelsString() const;
194 
196  std::string LogLevelToStr(BCLog::Level level) const;
197 
198  bool DefaultShrinkDebugFile() const;
199  };
200 
201 } // namespace BCLog
202 
204 
206 static inline bool LogAcceptCategory(BCLog::LogFlags category, BCLog::Level level)
207 {
208  return LogInstance().WillLogCategoryLevel(category, level);
209 }
210 
212 bool GetLogCategory(BCLog::LogFlags& flag, const std::string& str);
213 
214 // Be conservative when using LogPrintf/error or other things which
215 // unconditionally log to debug.log! It should not be the case that an inbound
216 // peer can fill up a user's disk with debug.log entries.
217 
218 template <typename... Args>
219 static inline void LogPrintf_(const std::string& logging_function, const std::string& source_file, const int source_line, const BCLog::LogFlags flag, const BCLog::Level level, const char* fmt, const Args&... args)
220 {
221  if (LogInstance().Enabled()) {
222  std::string log_msg;
223  try {
224  log_msg = tfm::format(fmt, args...);
225  } catch (tinyformat::format_error& fmterr) {
226  /* Original format string will have newline so don't add one here */
227  log_msg = "Error \"" + std::string(fmterr.what()) + "\" while formatting log message: " + fmt;
228  }
229  LogInstance().LogPrintStr(log_msg, logging_function, source_file, source_line, flag, level);
230  }
231 }
232 
233 #define LogPrintLevel_(category, level, ...) LogPrintf_(__func__, __FILE__, __LINE__, category, level, __VA_ARGS__)
234 
235 // Log unconditionally.
236 #define LogPrintf(...) LogPrintLevel_(BCLog::LogFlags::NONE, BCLog::Level::None, __VA_ARGS__)
237 
238 // Log unconditionally, prefixing the output with the passed category name.
239 #define LogPrintfCategory(category, ...) LogPrintLevel_(category, BCLog::Level::None, __VA_ARGS__)
240 
241 // Use a macro instead of a function for conditional logging to prevent
242 // evaluating arguments when logging for the category is not enabled.
243 
244 // Log conditionally, prefixing the output with the passed category name.
245 #define LogPrint(category, ...) \
246  do { \
247  if (LogAcceptCategory((category), BCLog::Level::Debug)) { \
248  LogPrintLevel_(category, BCLog::Level::None, __VA_ARGS__); \
249  } \
250  } while (0)
251 
252 // Log conditionally, prefixing the output with the passed category name and severity level.
253 #define LogPrintLevel(category, level, ...) \
254  do { \
255  if (LogAcceptCategory((category), (level))) { \
256  LogPrintLevel_(category, level, __VA_ARGS__); \
257  } \
258  } while (0)
259 
260 template <typename... Args>
261 bool error(const char* fmt, const Args&... args)
262 {
263  LogPrintf("ERROR: %s\n", tfm::format(fmt, args...));
264  return false;
265 }
266 
267 #endif // BITCOIN_LOGGING_H
bool m_buffering GUARDED_BY(m_cs)
Buffer messages before logging can be started.
bool WillLogCategory(LogFlags category) const
Definition: logging.cpp:122
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:112
bool Enabled() const
Returns whether logs will be written to any output.
Definition: logging.h:130
std::string LogTimestampStr(const std::string &str)
Definition: logging.cpp:344
void DisconnectTestLogger()
Only for testing.
Definition: logging.cpp:87
std::list< std::string > m_msgs_before_open GUARDED_BY(m_cs)
std::list< std::function< void(const std::string &)> >::iterator PushBackCallback(std::function< void(const std::string &)> fun)
Connect a slot to the print signal and return the connection.
Definition: logging.h:137
std::atomic< uint32_t > m_categories
Log categories bitfield.
Definition: logging.h:107
bool DefaultShrinkDebugFile() const
Definition: logging.cpp:140
std::unordered_map< LogFlags, Level > m_category_log_levels GUARDED_BY(m_cs)
Category-specific log level. Overrides m_log_level.
bool m_log_sourcelocations
Definition: logging.h:121
void SetLogLevel(Level level)
Definition: logging.h:171
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:104
Level LogLevel() const
Definition: logging.h:170
bool WillLogCategoryLevel(LogFlags category, Level level) const
Definition: logging.cpp:127
fs::path m_file_path
Definition: logging.h:123
std::unordered_map< LogFlags, Level > CategoryLevels() const
Definition: logging.h:158
bool m_log_time_micros
Definition: logging.h:119
bool m_log_threadnames
Definition: logging.h:120
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:97
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:392
std::vector< LogCategory > LogCategoriesList() const
Returns a vector of the log categories in alphabetical order.
Definition: logging.cpp:314
void EnableCategory(LogFlags flag)
Definition: logging.cpp:96
bool StartLogging()
Start logging (and flush all buffered messages)
Definition: logging.cpp:48
std::string LogLevelToStr(BCLog::Level level) const
Returns the string representation of a log level.
Definition: logging.cpp:204
bool m_log_timestamps
Definition: logging.h:118
FILE *m_fileout GUARDED_BY(m_cs)
std::string LogLevelsString() const
Returns a string with all user-selectable log levels.
Definition: logging.cpp:338
void DeleteCallback(std::list< std::function< void(const std::string &)>>::iterator it)
Delete a connection.
Definition: logging.h:145
std::atomic< bool > m_reopen_file
Definition: logging.h:124
void ShrinkDebugFile()
Definition: logging.cpp:461
bool m_print_to_file
Definition: logging.h:116
uint32_t GetCategoryMask() const
Definition: logging.h:174
void SetCategoryLogLevel(const std::unordered_map< LogFlags, Level > &levels)
Definition: logging.h:163
bool m_print_to_console
Definition: logging.h:115
StdMutex m_cs
Definition: logging.h:86
std::string LogCategoriesString() const
Returns a string with the log categories in alphabetical order.
Definition: logging.h:187
void DisableCategory(LogFlags flag)
Definition: logging.cpp:109
Path class wrapper to block calls to the fs::path(std::string) implicit constructor and the fs::path:...
Definition: fs.h:31
static const bool DEFAULT_LOGTIMESTAMPS
Definition: logging.h:25
static void LogPrintf_(const std::string &logging_function, const std::string &source_file, const int source_line, const BCLog::LogFlags flag, const BCLog::Level level, const char *fmt, const Args &... args)
Definition: logging.h:219
static const bool DEFAULT_LOGIPS
Definition: logging.h:24
static const bool DEFAULT_LOGTHREADNAMES
Definition: logging.h:26
static bool LogAcceptCategory(BCLog::LogFlags category, BCLog::Level level)
Return true if log accepts specified category, at the specified level.
Definition: logging.h:206
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:189
static const bool DEFAULT_LOGSOURCELOCATIONS
Definition: logging.h:27
bool fLogIPs
Definition: logging.cpp:41
bool error(const char *fmt, const Args &... args)
Definition: logging.h:261
static const bool DEFAULT_LOGTIMEMICROS
Definition: logging.h:23
const char *const DEFAULT_DEBUGLOGFILE
Definition: logging.cpp:17
#define LogPrintf(...)
Definition: logging.h:236
BCLog::Logger & LogInstance()
Definition: logging.cpp:20
Definition: timer.h:19
Level
Definition: logging.h:73
LogFlags
Definition: logging.h:38
@ ESTIMATEFEE
Definition: logging.h:48
@ TXRECONCILIATION
Definition: logging.h:69
@ RAND
Definition: logging.h:53
@ COINDB
Definition: logging.h:58
@ REINDEX
Definition: logging.h:51
@ WALLETDB
Definition: logging.h:46
@ SCAN
Definition: logging.h:70
@ ADDRMAN
Definition: logging.h:49
@ ALL
Definition: logging.h:71
@ RPC
Definition: logging.h:47
@ HTTP
Definition: logging.h:43
@ LEVELDB
Definition: logging.h:60
@ NONE
Definition: logging.h:39
@ VALIDATION
Definition: logging.h:61
@ MEMPOOLREJ
Definition: logging.h:56
@ PRUNE
Definition: logging.h:54
@ TOR
Definition: logging.h:41
@ LIBEVENT
Definition: logging.h:57
@ CMPCTBLOCK
Definition: logging.h:52
@ PROXY
Definition: logging.h:55
@ ZMQ
Definition: logging.h:45
@ IPC
Definition: logging.h:63
@ MEMPOOL
Definition: logging.h:42
@ SELECTCOINS
Definition: logging.h:50
@ I2P
Definition: logging.h:62
@ BENCH
Definition: logging.h:44
@ NET
Definition: logging.h:40
@ UTIL
Definition: logging.h:67
@ QT
Definition: logging.h:59
@ BLOCKSTORE
Definition: logging.h:68
constexpr auto DEFAULT_LOG_LEVEL
Definition: logging.h:81
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:1060
ArgsManager args
auto Join(const C &container, const S &separator, UnaryOp unary_op)
Join all container items.
Definition: string.h:68
bool active
Definition: logging.h:34
std::string category
Definition: logging.h:33
#define LOCK(cs)
Definition: sync.h:258