Bitcoin Core  24.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-2021 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  ALL = ~(uint32_t)0,
70  };
71  enum class Level {
72  Trace = 0, // High-volume or detailed logging for development/debugging
73  Debug, // Reasonably noisy logging, but still usable in production
74  Info, // Default
75  Warning,
76  Error,
77  None, // Internal use only
78  };
80 
81  class Logger
82  {
83  private:
84  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
85 
86  FILE* m_fileout GUARDED_BY(m_cs) = nullptr;
87  std::list<std::string> m_msgs_before_open GUARDED_BY(m_cs);
88  bool m_buffering GUARDED_BY(m_cs) = true;
89 
95  std::atomic_bool m_started_new_line{true};
96 
98  std::unordered_map<LogFlags, Level> m_category_log_levels GUARDED_BY(m_cs);
99 
102  std::atomic<Level> m_log_level{DEFAULT_LOG_LEVEL};
103 
105  std::atomic<uint32_t> m_categories{0};
106 
107  std::string LogTimestampStr(const std::string& str);
108 
110  std::list<std::function<void(const std::string&)>> m_print_callbacks GUARDED_BY(m_cs) {};
111 
112  public:
113  bool m_print_to_console = false;
114  bool m_print_to_file = false;
115 
120 
122  std::atomic<bool> m_reopen_file{false};
123 
125  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);
126 
128  bool Enabled() const
129  {
130  StdLockGuard scoped_lock(m_cs);
131  return m_buffering || m_print_to_console || m_print_to_file || !m_print_callbacks.empty();
132  }
133 
135  std::list<std::function<void(const std::string&)>>::iterator PushBackCallback(std::function<void(const std::string&)> fun)
136  {
137  StdLockGuard scoped_lock(m_cs);
138  m_print_callbacks.push_back(std::move(fun));
139  return --m_print_callbacks.end();
140  }
141 
143  void DeleteCallback(std::list<std::function<void(const std::string&)>>::iterator it)
144  {
145  StdLockGuard scoped_lock(m_cs);
146  m_print_callbacks.erase(it);
147  }
148 
150  bool StartLogging();
152  void DisconnectTestLogger();
153 
154  void ShrinkDebugFile();
155 
156  std::unordered_map<LogFlags, Level> CategoryLevels() const
157  {
158  StdLockGuard scoped_lock(m_cs);
159  return m_category_log_levels;
160  }
161  void SetCategoryLogLevel(const std::unordered_map<LogFlags, Level>& levels)
162  {
163  StdLockGuard scoped_lock(m_cs);
164  m_category_log_levels = levels;
165  }
166  bool SetCategoryLogLevel(const std::string& category_str, const std::string& level_str);
167 
168  Level LogLevel() const { return m_log_level.load(); }
169  void SetLogLevel(Level level) { m_log_level = level; }
170  bool SetLogLevel(const std::string& level);
171 
172  uint32_t GetCategoryMask() const { return m_categories.load(); }
173 
174  void EnableCategory(LogFlags flag);
175  bool EnableCategory(const std::string& str);
176  void DisableCategory(LogFlags flag);
177  bool DisableCategory(const std::string& str);
178 
179  bool WillLogCategory(LogFlags category) const;
180  bool WillLogCategoryLevel(LogFlags category, Level level) const;
181 
183  std::vector<LogCategory> LogCategoriesList() const;
185  std::string LogCategoriesString() const
186  {
187  return Join(LogCategoriesList(), ", ", [&](const LogCategory& i) { return i.category; });
188  };
189 
191  std::string LogLevelsString() const;
192 
194  std::string LogLevelToStr(BCLog::Level level) const;
195 
196  bool DefaultShrinkDebugFile() const;
197  };
198 
199 } // namespace BCLog
200 
202 
204 static inline bool LogAcceptCategory(BCLog::LogFlags category, BCLog::Level level)
205 {
206  return LogInstance().WillLogCategoryLevel(category, level);
207 }
208 
210 bool GetLogCategory(BCLog::LogFlags& flag, const std::string& str);
211 
212 // Be conservative when using LogPrintf/error or other things which
213 // unconditionally log to debug.log! It should not be the case that an inbound
214 // peer can fill up a user's disk with debug.log entries.
215 
216 template <typename... Args>
217 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)
218 {
219  if (LogInstance().Enabled()) {
220  std::string log_msg;
221  try {
222  log_msg = tfm::format(fmt, args...);
223  } catch (tinyformat::format_error& fmterr) {
224  /* Original format string will have newline so don't add one here */
225  log_msg = "Error \"" + std::string(fmterr.what()) + "\" while formatting log message: " + fmt;
226  }
227  LogInstance().LogPrintStr(log_msg, logging_function, source_file, source_line, flag, level);
228  }
229 }
230 
231 #define LogPrintLevel_(category, level, ...) LogPrintf_(__func__, __FILE__, __LINE__, category, level, __VA_ARGS__)
232 
233 // Log unconditionally.
234 #define LogPrintf(...) LogPrintLevel_(BCLog::LogFlags::NONE, BCLog::Level::None, __VA_ARGS__)
235 
236 // Log unconditionally, prefixing the output with the passed category name.
237 #define LogPrintfCategory(category, ...) LogPrintLevel_(category, BCLog::Level::None, __VA_ARGS__)
238 
239 // Use a macro instead of a function for conditional logging to prevent
240 // evaluating arguments when logging for the category is not enabled.
241 
242 // Log conditionally, prefixing the output with the passed category name.
243 #define LogPrint(category, ...) \
244  do { \
245  if (LogAcceptCategory((category), BCLog::Level::Debug)) { \
246  LogPrintLevel_(category, BCLog::Level::None, __VA_ARGS__); \
247  } \
248  } while (0)
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 #endif // BITCOIN_LOGGING_H
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:385
void EnableCategory(LogFlags flag)
Definition: logging.cpp:96
StdMutex m_cs
Definition: logging.h:84
FILE *m_fileout GUARDED_BY(m_cs)
void SetCategoryLogLevel(const std::unordered_map< LogFlags, Level > &levels)
Definition: logging.h:161
fs::path m_file_path
Definition: logging.h:121
Definition: timer.h:18
Level LogLevel() const
Definition: logging.h:168
bool fLogIPs
Definition: logging.cpp:41
std::string LogLevelToStr(BCLog::Level level) const
Returns the string representation of a log level.
Definition: logging.cpp:202
static const bool DEFAULT_LOGTHREADNAMES
Definition: logging.h:26
static const bool DEFAULT_LOGTIMEMICROS
Definition: logging.h:23
std::atomic< bool > m_reopen_file
Definition: logging.h:122
bool m_print_to_console
Definition: logging.h:113
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:217
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:102
BCLog::Logger & LogInstance()
Definition: logging.cpp:20
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:135
bool m_log_sourcelocations
Definition: logging.h:119
ArgsManager args
bool m_print_to_file
Definition: logging.h:114
constexpr auto DEFAULT_LOG_LEVEL
Definition: logging.h:79
std::string category
Definition: logging.h:33
bool m_log_threadnames
Definition: logging.h:118
bool m_log_time_micros
Definition: logging.h:117
#define LOCK(cs)
Definition: sync.h:261
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:1062
std::unordered_map< LogFlags, Level > CategoryLevels() const
Definition: logging.h:156
uint32_t GetCategoryMask() const
Definition: logging.h:172
void DisableCategory(LogFlags flag)
Definition: logging.cpp:109
void SetLogLevel(Level level)
Definition: logging.h:169
bool WillLogCategory(LogFlags category) const
Definition: logging.cpp:122
std::atomic< uint32_t > m_categories
Log categories bitfield.
Definition: logging.h:105
Level
Definition: logging.h:71
void DisconnectTestLogger()
Only for testing.
Definition: logging.cpp:87
bool StartLogging()
Start logging (and flush all buffered messages)
Definition: logging.cpp:48
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:110
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:95
auto Join(const C &container, const S &separator, UnaryOp unary_op)
Join all container items.
Definition: string.h:68
static const bool DEFAULT_LOGSOURCELOCATIONS
Definition: logging.h:27
void DeleteCallback(std::list< std::function< void(const std::string &)>>::iterator it)
Delete a connection.
Definition: logging.h:143
bool active
Definition: logging.h:34
LogFlags
Definition: logging.h:38
std::string LogLevelsString() const
Returns a string with all user-selectable log levels.
Definition: logging.cpp:332
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:187
std::vector< LogCategory > LogCategoriesList() const
Returns a vector of the log categories in alphabetical order.
Definition: logging.cpp:308
static bool LogAcceptCategory(BCLog::LogFlags category, BCLog::Level level)
Return true if log accepts specified category, at the specified level.
Definition: logging.h:204
bool m_log_timestamps
Definition: logging.h:116
static const bool DEFAULT_LOGIPS
Definition: logging.h:24
const char *const DEFAULT_DEBUGLOGFILE
Definition: logging.cpp:17
bool Enabled() const
Returns whether logs will be written to any output.
Definition: logging.h:128
Path class wrapper to block calls to the fs::path(std::string) implicit constructor and the fs::path:...
Definition: fs.h:30
static const bool DEFAULT_LOGTIMESTAMPS
Definition: logging.h:25
std::string LogCategoriesString() const
Returns a string with the log categories in alphabetical order.
Definition: logging.h:185
void ShrinkDebugFile()
Definition: logging.cpp:454
std::string LogTimestampStr(const std::string &str)
Definition: logging.cpp:338
bool WillLogCategoryLevel(LogFlags category, Level level) const
Definition: logging.cpp:127
bool DefaultShrinkDebugFile() const
Definition: logging.cpp:140