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