Bitcoin ABC  0.29.2
P2P Digital Currency
logging.h
Go to the documentation of this file.
1 // Copyright (c) 2009-2010 Satoshi Nakamoto
2 // Copyright (c) 2009-2016 The Bitcoin Core developers
3 // Copyright (c) 2017-2019 The Bitcoin developers
4 // Distributed under the MIT software license, see the accompanying
5 // file COPYING or http://www.opensource.org/licenses/mit-license.php.
6 
7 #ifndef BITCOIN_LOGGING_H
8 #define BITCOIN_LOGGING_H
9 
10 #include <fs.h>
11 #include <threadsafety.h>
12 #include <tinyformat.h>
13 #include <util/string.h>
14 
15 #include <atomic>
16 #include <cstdint>
17 #include <functional>
18 #include <list>
19 #include <mutex>
20 #include <string>
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 
28 extern bool fLogIPs;
29 extern const char *const DEFAULT_DEBUGLOGFILE;
30 
31 struct LogCategory {
32  std::string category;
33  bool active;
34 };
35 
36 namespace BCLog {
37 
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  AVALANCHE = (1 << 22),
63  I2P = (1 << 23),
64  CHRONIK = (1 << 24),
65 #ifdef DEBUG_LOCKCONTENTION
66  LOCK = (1 << 25),
67 #endif
68  BLOCKSTORE = (1 << 26),
69  NETDEBUG = (1 << 27),
70  ALL = ~uint32_t(0),
71 };
72 
73 class Logger {
74 private:
75  // Can not use Mutex from sync.h because in debug mode it would cause a
76  // deadlock when a potential deadlock was detected
77  mutable StdMutex m_cs;
78 
79  FILE *m_fileout GUARDED_BY(m_cs) = nullptr;
80  std::list<std::string> m_msgs_before_open GUARDED_BY(m_cs);
82  bool m_buffering GUARDED_BY(m_cs) = true;
83 
88  std::atomic_bool m_started_new_line{true};
89 
93  std::atomic<uint32_t> m_categories{0};
94 
95  std::string LogTimestampStr(const std::string &str);
96 
98  std::list<std::function<void(const std::string &)>>
99  m_print_callbacks GUARDED_BY(m_cs){};
100 
101 public:
102  bool m_print_to_console = false;
103  bool m_print_to_file = false;
104 
109 
111  std::atomic<bool> m_reopen_file{false};
112 
113  ~Logger();
114 
116  void LogPrintStr(const std::string &str,
117  const std::string &logging_function,
118  const std::string &source_file, const int source_line);
119 
121  bool Enabled() const {
122  StdLockGuard scoped_lock(m_cs);
123  return m_buffering || m_print_to_console || m_print_to_file ||
124  !m_print_callbacks.empty();
125  }
126 
128  std::list<std::function<void(const std::string &)>>::iterator
129  PushBackCallback(std::function<void(const std::string &)> fun) {
130  StdLockGuard scoped_lock(m_cs);
131  m_print_callbacks.push_back(std::move(fun));
132  return --m_print_callbacks.end();
133  }
134 
137  std::list<std::function<void(const std::string &)>>::iterator it) {
138  StdLockGuard scoped_lock(m_cs);
139  m_print_callbacks.erase(it);
140  }
141 
143  bool StartLogging();
145  void DisconnectTestLogger();
146 
147  void ShrinkDebugFile();
148 
149  uint32_t GetCategoryMask() const { return m_categories.load(); }
150 
151  void EnableCategory(LogFlags category);
152  bool EnableCategory(const std::string &str);
153  void DisableCategory(LogFlags category);
154  bool DisableCategory(const std::string &str);
155 
157  bool WillLogCategory(LogFlags category) const;
158 
160  std::vector<LogCategory> LogCategoriesList() const;
162  std::string LogCategoriesString() const {
163  return Join(LogCategoriesList(), ", ",
164  [&](const LogCategory &i) { return i.category; });
165  };
166 
168  bool DefaultShrinkDebugFile() const;
169 };
170 
171 } // namespace BCLog
172 
174 
176 static inline bool LogAcceptCategory(BCLog::LogFlags category) {
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 template <typename... Args>
187 static inline void
188 LogPrintf_(const std::string &logging_function, const std::string &source_file,
189  const int source_line, const char *fmt, const Args &...args) {
190  if (LogInstance().Enabled()) {
191  std::string log_msg;
192  try {
193  log_msg = tfm::format(fmt, args...);
194  } catch (tinyformat::format_error &fmterr) {
198  log_msg = "Error \"" + std::string(fmterr.what()) +
199  "\" while formatting log message: " + fmt;
200  }
201  LogInstance().LogPrintStr(log_msg, logging_function, source_file,
202  source_line);
203  }
204 }
205 
206 #define LogPrintf(...) LogPrintf_(__func__, __FILE__, __LINE__, __VA_ARGS__)
207 
208 // Use a macro instead of a function for conditional logging to prevent
209 // evaluating arguments when logging for the category is not enabled.
210 #define LogPrint(category, ...) \
211  do { \
212  if (LogAcceptCategory((category))) { \
213  LogPrintf(__VA_ARGS__); \
214  } \
215  } while (0)
216 
222 #define LogPrintfToBeContinued LogPrintf
223 #define LogPrintToBeContinued LogPrint
224 
225 #endif // BITCOIN_LOGGING_H
bool m_buffering GUARDED_BY(m_cs)
Buffer messages before logging can be started.
bool WillLogCategory(LogFlags category) const
Return true if log accepts specified category.
Definition: logging.cpp:350
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:129
bool Enabled() const
Returns whether logs will be written to any output.
Definition: logging.h:121
std::string LogTimestampStr(const std::string &str)
Definition: logging.cpp:183
void DisconnectTestLogger()
Only for testing.
Definition: logging.cpp:89
std::list< std::string > m_msgs_before_open GUARDED_BY(m_cs)
std::atomic< uint32_t > m_categories
Log categories bitfield.
Definition: logging.h:93
bool DefaultShrinkDebugFile() const
Default for whether ShrinkDebugFile should be run.
Definition: logging.cpp:362
bool m_log_sourcelocations
Definition: logging.h:108
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:99
fs::path m_file_path
Definition: logging.h:110
bool m_log_time_micros
Definition: logging.h:106
bool m_log_threadnames
Definition: logging.h:107
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:88
std::vector< LogCategory > LogCategoriesList() const
Returns a vector of the log categories in alphabetical order.
Definition: logging.cpp:155
void DisableCategory(LogFlags category)
Definition: logging.cpp:337
void EnableCategory(LogFlags category)
Definition: logging.cpp:324
bool StartLogging()
Start logging (and flush all buffered messages)
Definition: logging.cpp:44
bool m_log_timestamps
Definition: logging.h:105
FILE *m_fileout GUARDED_BY(m_cs)
void DeleteCallback(std::list< std::function< void(const std::string &)>>::iterator it)
Delete a connection.
Definition: logging.h:136
std::atomic< bool > m_reopen_file
Definition: logging.h:111
void ShrinkDebugFile()
Definition: logging.cpp:285
bool m_print_to_file
Definition: logging.h:103
uint32_t GetCategoryMask() const
Definition: logging.h:149
bool m_print_to_console
Definition: logging.h:102
StdMutex m_cs
Definition: logging.h:77
void LogPrintStr(const std::string &str, const std::string &logging_function, const std::string &source_file, const int source_line)
Send a string to the log output.
Definition: logging.cpp:232
std::string LogCategoriesString() const
Returns a string with the log categories in alphabetical order.
Definition: logging.h:162
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:24
static bool LogAcceptCategory(BCLog::LogFlags category)
Return true if log accepts specified category.
Definition: logging.h:176
static void LogPrintf_(const std::string &logging_function, const std::string &source_file, const int source_line, const char *fmt, const Args &...args)
Definition: logging.h:188
static const bool DEFAULT_LOGIPS
Definition: logging.h:23
static const bool DEFAULT_LOGTHREADNAMES
Definition: logging.h:25
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:141
static const bool DEFAULT_LOGSOURCELOCATIONS
Definition: logging.h:26
bool fLogIPs
Definition: logging.cpp:17
static const bool DEFAULT_LOGTIMEMICROS
Definition: logging.h:22
const char *const DEFAULT_DEBUGLOGFILE
Definition: logging.cpp:18
BCLog::Logger & LogInstance()
Definition: logging.cpp:20
Definition: timer.h:17
LogFlags
Definition: logging.h:38
@ ESTIMATEFEE
Definition: logging.h:48
@ AVALANCHE
Definition: logging.h:62
@ RAND
Definition: logging.h:53
@ COINDB
Definition: logging.h:58
@ REINDEX
Definition: logging.h:51
@ WALLETDB
Definition: logging.h:46
@ ADDRMAN
Definition: logging.h:49
@ ALL
Definition: logging.h:70
@ NETDEBUG
Definition: logging.h:69
@ 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
@ CHRONIK
Definition: logging.h:64
@ ZMQ
Definition: logging.h:45
@ MEMPOOL
Definition: logging.h:42
@ SELECTCOINS
Definition: logging.h:50
@ I2P
Definition: logging.h:63
@ BENCH
Definition: logging.h:44
@ NET
Definition: logging.h:40
@ QT
Definition: logging.h:59
@ BLOCKSTORE
Definition: logging.h:68
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:1112
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:54
bool active
Definition: logging.h:33
std::string category
Definition: logging.h:32
#define LOCK(cs)
Definition: sync.h:306