Bitcoin Core  23.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-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 <tinyformat.h>
11 #include <threadsafety.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 <vector>
21 
22 static const bool DEFAULT_LOGTIMEMICROS = false;
23 static const bool DEFAULT_LOGIPS = false;
24 static const bool DEFAULT_LOGTIMESTAMPS = true;
25 static const bool DEFAULT_LOGTHREADNAMES = false;
26 static const bool DEFAULT_LOGSOURCELOCATIONS = false;
27 extern const char * const DEFAULT_DEBUGLOGFILE;
28 
29 extern bool fLogIPs;
30 
31 struct LogCategory {
32  std::string category;
33  bool active;
34 };
35 
36 namespace BCLog {
37  enum LogFlags : uint32_t {
38  NONE = 0,
39  NET = (1 << 0),
40  TOR = (1 << 1),
41  MEMPOOL = (1 << 2),
42  HTTP = (1 << 3),
43  BENCH = (1 << 4),
44  ZMQ = (1 << 5),
45  WALLETDB = (1 << 6),
46  RPC = (1 << 7),
47  ESTIMATEFEE = (1 << 8),
48  ADDRMAN = (1 << 9),
49  SELECTCOINS = (1 << 10),
50  REINDEX = (1 << 11),
51  CMPCTBLOCK = (1 << 12),
52  RAND = (1 << 13),
53  PRUNE = (1 << 14),
54  PROXY = (1 << 15),
55  MEMPOOLREJ = (1 << 16),
56  LIBEVENT = (1 << 17),
57  COINDB = (1 << 18),
58  QT = (1 << 19),
59  LEVELDB = (1 << 20),
60  VALIDATION = (1 << 21),
61  I2P = (1 << 22),
62  IPC = (1 << 23),
63 #ifdef DEBUG_LOCKCONTENTION
64  LOCK = (1 << 24),
65 #endif
66  UTIL = (1 << 25),
67  BLOCKSTORE = (1 << 26),
68  ALL = ~(uint32_t)0,
69  };
70  enum class Level {
71  Debug = 0,
72  None = 1,
73  Info = 2,
74  Warning = 3,
75  Error = 4,
76  };
77 
78  class Logger
79  {
80  private:
81  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
82 
83  FILE* m_fileout GUARDED_BY(m_cs) = nullptr;
84  std::list<std::string> m_msgs_before_open GUARDED_BY(m_cs);
85  bool m_buffering GUARDED_BY(m_cs) = true;
86 
92  std::atomic_bool m_started_new_line{true};
93 
95  std::atomic<uint32_t> m_categories{0};
96 
97  std::string LogTimestampStr(const std::string& str);
98 
100  std::list<std::function<void(const std::string&)>> m_print_callbacks GUARDED_BY(m_cs) {};
101 
102  public:
103  bool m_print_to_console = false;
104  bool m_print_to_file = false;
105 
110 
112  std::atomic<bool> m_reopen_file{false};
113 
115  void LogPrintStr(const std::string& str, const std::string& logging_function, const std::string& source_file, const int source_line, const BCLog::LogFlags category, const BCLog::Level level);
116 
118  bool Enabled() const
119  {
120  StdLockGuard scoped_lock(m_cs);
121  return m_buffering || m_print_to_console || m_print_to_file || !m_print_callbacks.empty();
122  }
123 
125  std::list<std::function<void(const std::string&)>>::iterator PushBackCallback(std::function<void(const std::string&)> fun)
126  {
127  StdLockGuard scoped_lock(m_cs);
128  m_print_callbacks.push_back(std::move(fun));
129  return --m_print_callbacks.end();
130  }
131 
133  void DeleteCallback(std::list<std::function<void(const std::string&)>>::iterator it)
134  {
135  StdLockGuard scoped_lock(m_cs);
136  m_print_callbacks.erase(it);
137  }
138 
140  bool StartLogging();
142  void DisconnectTestLogger();
143 
144  void ShrinkDebugFile();
145 
146  uint32_t GetCategoryMask() const { return m_categories.load(); }
147 
148  void EnableCategory(LogFlags flag);
149  bool EnableCategory(const std::string& str);
150  void DisableCategory(LogFlags flag);
151  bool DisableCategory(const std::string& str);
152 
153  bool WillLogCategory(LogFlags category) const;
155  std::vector<LogCategory> LogCategoriesList() const;
157  std::string LogCategoriesString() const
158  {
159  return Join(LogCategoriesList(), ", ", [&](const LogCategory& i) { return i.category; });
160  };
161 
162  bool DefaultShrinkDebugFile() const;
163  };
164 
165 } // namespace BCLog
166 
168 
170 static inline bool LogAcceptCategory(BCLog::LogFlags category, BCLog::Level level)
171 {
172  // Log messages at Warning and Error level unconditionally, so that
173  // important troubleshooting information doesn't get lost.
174  if (level >= BCLog::Level::Warning) {
175  return true;
176  }
177  return LogInstance().WillLogCategory(category);
178 }
179 
181 bool GetLogCategory(BCLog::LogFlags& flag, const std::string& str);
182 
183 // Be conservative when using LogPrintf/error or other things which
184 // unconditionally log to debug.log! It should not be the case that an inbound
185 // peer can fill up a user's disk with debug.log entries.
186 
187 template <typename... Args>
188 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)
189 {
190  if (LogInstance().Enabled()) {
191  std::string log_msg;
192  try {
193  log_msg = tfm::format(fmt, args...);
194  } catch (tinyformat::format_error& fmterr) {
195  /* Original format string will have newline so don't add one here */
196  log_msg = "Error \"" + std::string(fmterr.what()) + "\" while formatting log message: " + fmt;
197  }
198  LogInstance().LogPrintStr(log_msg, logging_function, source_file, source_line, flag, level);
199  }
200 }
201 
202 #define LogPrintLevel_(category, level, ...) LogPrintf_(__func__, __FILE__, __LINE__, category, level, __VA_ARGS__)
203 
204 // Log unconditionally.
205 #define LogPrintf(...) LogPrintLevel_(BCLog::LogFlags::NONE, BCLog::Level::None, __VA_ARGS__)
206 
207 // Log unconditionally, prefixing the output with the passed category name.
208 #define LogPrintfCategory(category, ...) LogPrintLevel_(category, BCLog::Level::None, __VA_ARGS__)
209 
210 // Use a macro instead of a function for conditional logging to prevent
211 // evaluating arguments when logging for the category is not enabled.
212 
213 // Log conditionally, prefixing the output with the passed category name.
214 #define LogPrint(category, ...) \
215  do { \
216  if (LogAcceptCategory((category), BCLog::Level::Debug)) { \
217  LogPrintLevel_(category, BCLog::Level::None, __VA_ARGS__); \
218  } \
219  } while (0)
220 
221 // Log conditionally, prefixing the output with the passed category name and severity level.
222 #define LogPrintLevel(category, level, ...) \
223  do { \
224  if (LogAcceptCategory((category), (level))) { \
225  LogPrintLevel_(category, level, __VA_ARGS__); \
226  } \
227  } while (0)
228 
229 #endif // BITCOIN_LOGGING_H
DEFAULT_LOGTIMEMICROS
static const bool DEFAULT_LOGTIMEMICROS
Definition: logging.h:22
BCLog::LogFlags
LogFlags
Definition: logging.h:37
BCLog::Logger::m_print_to_file
bool m_print_to_file
Definition: logging.h:104
BCLog::IPC
@ IPC
Definition: logging.h:62
BCLog::Logger::DeleteCallback
void DeleteCallback(std::list< std::function< void(const std::string &)>>::iterator it)
Delete a connection.
Definition: logging.h:133
BCLog::ZMQ
@ ZMQ
Definition: logging.h:44
tinyformat::format
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
BCLog::I2P
@ I2P
Definition: logging.h:61
BCLog::Level::Debug
@ Debug
BCLog::HTTP
@ HTTP
Definition: logging.h:42
LogCategory::active
bool active
Definition: logging.h:33
fs.h
BCLog::Level
Level
Definition: logging.h:70
BCLog::Logger::WillLogCategory
bool WillLogCategory(LogFlags category) const
Definition: logging.cpp:120
BCLog::Logger::m_categories
std::atomic< uint32_t > m_categories
Log categories bitfield.
Definition: logging.h:95
BCLog::Logger::StartLogging
bool StartLogging()
Start logging (and flush all buffered messages)
Definition: logging.cpp:46
string.h
DEFAULT_LOGIPS
static const bool DEFAULT_LOGIPS
Definition: logging.h:23
DEFAULT_DEBUGLOGFILE
const char *const DEFAULT_DEBUGLOGFILE
Definition: logging.cpp:16
LogCategory::category
std::string category
Definition: logging.h:32
BCLog::BENCH
@ BENCH
Definition: logging.h:43
BCLog::Logger::GetCategoryMask
uint32_t GetCategoryMask() const
Definition: logging.h:146
LogInstance
BCLog::Logger & LogInstance()
Definition: logging.cpp:18
DEFAULT_LOGTIMESTAMPS
static const bool DEFAULT_LOGTIMESTAMPS
Definition: logging.h:24
BCLog::ESTIMATEFEE
@ ESTIMATEFEE
Definition: logging.h:47
BCLog::Logger::LogCategoriesList
std::vector< LogCategory > LogCategoriesList() const
Returns a vector of the log categories in alphabetical order.
Definition: logging.cpp:272
BCLog::PROXY
@ PROXY
Definition: logging.h:54
BCLog::PRUNE
@ PRUNE
Definition: logging.h:53
BCLog::Logger::DisconnectTestLogger
void DisconnectTestLogger()
Only for testing.
Definition: logging.cpp:85
BCLog::MEMPOOLREJ
@ MEMPOOLREJ
Definition: logging.h:55
LogPrintf_
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:188
tinyformat.h
BCLog::Logger::m_cs
StdMutex m_cs
Definition: logging.h:81
BCLog::RPC
@ RPC
Definition: logging.h:46
BCLog::Logger::m_log_timestamps
bool m_log_timestamps
Definition: logging.h:106
StdLockGuard
Definition: threadsafety.h:70
BCLog::Level::Warning
@ Warning
BCLog::Level::Info
@ Info
BCLog::Logger::GUARDED_BY
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:100
BCLog::WALLETDB
@ WALLETDB
Definition: logging.h:45
threadsafety.h
BCLog::Logger::m_started_new_line
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:92
fs::path
Path class wrapper to block calls to the fs::path(std::string) implicit constructor and the fs::path:...
Definition: fs.h:30
BCLog::Logger::LogCategoriesString
std::string LogCategoriesString() const
Returns a string with the log categories in alphabetical order.
Definition: logging.h:157
BCLog::LEVELDB
@ LEVELDB
Definition: logging.h:59
BCLog::Logger::ShrinkDebugFile
void ShrinkDebugFile()
Definition: logging.cpp:406
BCLog::LIBEVENT
@ LIBEVENT
Definition: logging.h:56
BCLog::Logger::LogTimestampStr
std::string LogTimestampStr(const std::string &str)
Definition: logging.cpp:290
LogCategory
Definition: logging.h:31
BCLog::Logger::EnableCategory
void EnableCategory(LogFlags flag)
Definition: logging.cpp:94
BCLog::Logger::m_reopen_file
std::atomic< bool > m_reopen_file
Definition: logging.h:112
BCLog::TOR
@ TOR
Definition: logging.h:40
BCLog::REINDEX
@ REINDEX
Definition: logging.h:50
DEFAULT_LOGSOURCELOCATIONS
static const bool DEFAULT_LOGSOURCELOCATIONS
Definition: logging.h:26
BCLog::QT
@ QT
Definition: logging.h:58
BCLog::ALL
@ ALL
Definition: logging.h:68
BCLog::VALIDATION
@ VALIDATION
Definition: logging.h:60
BCLog::UTIL
@ UTIL
Definition: logging.h:66
StdMutex
Definition: threadsafety.h:57
BCLog::Logger::Enabled
bool Enabled() const
Returns whether logs will be written to any output.
Definition: logging.h:118
BCLog::Logger::GUARDED_BY
FILE *m_fileout GUARDED_BY(m_cs)
tinyformat::format_error
Definition: tinyformat.h:182
BCLog::Logger::m_log_sourcelocations
bool m_log_sourcelocations
Definition: logging.h:109
BCLog::BLOCKSTORE
@ BLOCKSTORE
Definition: logging.h:67
BCLog::Logger::m_file_path
fs::path m_file_path
Definition: logging.h:111
BCLog::RAND
@ RAND
Definition: logging.h:52
DEFAULT_LOGTHREADNAMES
static const bool DEFAULT_LOGTHREADNAMES
Definition: logging.h:25
BCLog::Logger::LogPrintStr
void LogPrintStr(const std::string &str, const std::string &logging_function, const std::string &source_file, const int source_line, const BCLog::LogFlags category, const BCLog::Level level)
Send a string to the log output.
Definition: logging.cpp:337
Join
auto Join(const std::vector< T > &list, const BaseType &separator, UnaryOp unary_op) -> decltype(unary_op(list.at(0)))
Join a list of items.
Definition: string.h:68
fLogIPs
bool fLogIPs
Definition: logging.cpp:39
BCLog::COINDB
@ COINDB
Definition: logging.h:57
BCLog::Logger::DefaultShrinkDebugFile
bool DefaultShrinkDebugFile() const
Definition: logging.cpp:125
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:172
BCLog
Definition: timer.h:18
BCLog::MEMPOOL
@ MEMPOOL
Definition: logging.h:41
BCLog::Logger::m_print_to_console
bool m_print_to_console
Definition: logging.h:103
LOCK
#define LOCK(cs)
Definition: sync.h:261
BCLog::Logger
Definition: logging.h:78
LogAcceptCategory
static bool LogAcceptCategory(BCLog::LogFlags category, BCLog::Level level)
Return true if log accepts specified category, at the specified level.
Definition: logging.h:170
BCLog::Logger::m_log_time_micros
bool m_log_time_micros
Definition: logging.h:107
BCLog::Logger::PushBackCallback
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:125
BCLog::SELECTCOINS
@ SELECTCOINS
Definition: logging.h:49
BCLog::Level::Error
@ Error
BCLog::ADDRMAN
@ ADDRMAN
Definition: logging.h:48
BCLog::Logger::DisableCategory
void DisableCategory(LogFlags flag)
Definition: logging.cpp:107
BCLog::NET
@ NET
Definition: logging.h:39
BCLog::CMPCTBLOCK
@ CMPCTBLOCK
Definition: logging.h:51
BCLog::Level::None
@ None
BCLog::Logger::m_log_threadnames
bool m_log_threadnames
Definition: logging.h:108
args
ArgsManager args
Definition: notifications.cpp:36
BCLog::NONE
@ NONE
Definition: logging.h:38