Bitcoin ABC 0.30.7
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 <threadsafety.h>
11#include <tinyformat.h>
12#include <util/fs.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
22static const bool DEFAULT_LOGTIMEMICROS = false;
23static const bool DEFAULT_LOGIPS = false;
24static const bool DEFAULT_LOGTIMESTAMPS = true;
25static const bool DEFAULT_LOGTHREADNAMES = false;
26static const bool DEFAULT_LOGSOURCELOCATIONS = false;
27
28extern bool fLogIPs;
29extern const char *const DEFAULT_DEBUGLOGFILE;
30
32 std::string category;
33 bool active;
34};
35
36namespace BCLog {
37
38enum 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 TXPACKAGES = (1 << 28),
71 ALL = ~uint32_t(0),
72};
73
74enum class Level {
75 Debug = 0,
76 None = 1,
77 Info = 2,
78 Warning = 3,
79 Error = 4,
80};
81
82class Logger {
83private:
84 // Can not use Mutex from sync.h because in debug mode it would cause a
85 // deadlock when a potential deadlock was detected
86 mutable StdMutex m_cs;
87
88 FILE *m_fileout GUARDED_BY(m_cs) = nullptr;
89 std::list<std::string> m_msgs_before_open GUARDED_BY(m_cs);
91 bool m_buffering GUARDED_BY(m_cs) = true;
92
97 std::atomic_bool m_started_new_line{true};
98
102 std::atomic<uint32_t> m_categories{0};
103
104 std::string LogTimestampStr(const std::string &str);
105
107 std::list<std::function<void(const std::string &)>>
108 m_print_callbacks GUARDED_BY(m_cs){};
109
110public:
111 bool m_print_to_console = false;
112 bool m_print_to_file = false;
113
118
120 std::atomic<bool> m_reopen_file{false};
121
122 ~Logger();
123
125 void LogPrintStr(const std::string &str,
126 const std::string &logging_function,
127 const std::string &source_file, const int source_line,
128 const BCLog::LogFlags category, const BCLog::Level level);
129
131 bool Enabled() const {
132 StdLockGuard scoped_lock(m_cs);
133 return m_buffering || m_print_to_console || m_print_to_file ||
134 !m_print_callbacks.empty();
135 }
136
138 std::list<std::function<void(const std::string &)>>::iterator
139 PushBackCallback(std::function<void(const std::string &)> fun) {
140 StdLockGuard scoped_lock(m_cs);
141 m_print_callbacks.push_back(std::move(fun));
142 return --m_print_callbacks.end();
143 }
144
147 std::list<std::function<void(const std::string &)>>::iterator it) {
148 StdLockGuard scoped_lock(m_cs);
149 m_print_callbacks.erase(it);
150 }
151
153 bool StartLogging();
156
157 void ShrinkDebugFile();
158
159 uint32_t GetCategoryMask() const { return m_categories.load(); }
160
161 void EnableCategory(LogFlags category);
162 bool EnableCategory(const std::string &str);
163 void DisableCategory(LogFlags category);
164 bool DisableCategory(const std::string &str);
165
167 bool WillLogCategory(LogFlags category) const;
168
170 std::vector<LogCategory> LogCategoriesList() const;
172 std::string LogCategoriesString() const {
173 return Join(LogCategoriesList(), ", ",
174 [&](const LogCategory &i) { return i.category; });
175 };
176
178 bool DefaultShrinkDebugFile() const;
179};
180
181} // namespace BCLog
182
184
186static inline bool LogAcceptCategory(BCLog::LogFlags category,
187 BCLog::Level level) {
188 // Log messages at Warning and Error level unconditionally, so that
189 // important troubleshooting information doesn't get lost.
190 if (level >= BCLog::Level::Warning) {
191 return true;
192 }
193 return LogInstance().WillLogCategory(category);
194}
195
197bool GetLogCategory(BCLog::LogFlags &flag, const std::string &str);
198
199// Be conservative when using LogPrintf/error or other things which
200// unconditionally log to debug.log! It should not be the case that an inbound
201// peer can fill up a user's disk with debug.log entries.
202template <typename... Args>
203static inline void
204LogPrintf_(const std::string &logging_function, const std::string &source_file,
205 const int source_line, const BCLog::LogFlags flag,
206 const BCLog::Level level, const char *fmt, const Args &...args) {
207 if (LogInstance().Enabled()) {
208 std::string log_msg;
209 try {
210 log_msg = tfm::format(fmt, args...);
211 } catch (tinyformat::format_error &fmterr) {
215 log_msg = "Error \"" + std::string(fmterr.what()) +
216 "\" while formatting log message: " + fmt;
217 }
218 LogInstance().LogPrintStr(log_msg, logging_function, source_file,
219 source_line, flag, level);
220 }
221}
222
223#define LogPrintLevel_(category, level, ...) \
224 LogPrintf_(__func__, __FILE__, __LINE__, category, level, __VA_ARGS__)
225
226// Log unconditionally.
227#define LogPrintf(...) \
228 LogPrintLevel_(BCLog::LogFlags::NONE, BCLog::Level::None, __VA_ARGS__)
229
230// Log unconditionally, prefixing the output with the passed category name.
231#define LogPrintfCategory(category, ...) \
232 LogPrintLevel_(category, BCLog::Level::None, __VA_ARGS__)
233
234// Use a macro instead of a function for conditional logging to prevent
235// evaluating arguments when logging for the category is not enabled.
236
237// Log conditionally, prefixing the output with the passed category name.
238#define LogPrint(category, ...) \
239 do { \
240 if (LogAcceptCategory((category), BCLog::Level::Debug)) { \
241 LogPrintLevel_(category, BCLog::Level::None, __VA_ARGS__); \
242 } \
243 } while (0)
244
245// Log conditionally, prefixing the output with the passed category name and
246// severity level.
247#define LogPrintLevel(category, level, ...) \
248 do { \
249 if (LogAcceptCategory((category), (level))) { \
250 LogPrintLevel_(category, level, __VA_ARGS__); \
251 } \
252 } while (0)
253
259#define LogPrintfToBeContinued LogPrintf
260#define LogPrintToBeContinued LogPrint
261#define LogPrintLevelToBeContinued LogPrintLevel
262
263template <typename... Args> bool error(const char *fmt, const Args &...args) {
264 LogPrintf("ERROR: %s\n", tfm::format(fmt, args...));
265 return false;
266}
267
268#endif // BITCOIN_LOGGING_H
FILE *m_fileout GUARDED_BY(m_cs)
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:400
bool Enabled() const
Returns whether logs will be written to any output.
Definition: logging.h:131
std::string LogTimestampStr(const std::string &str)
Definition: logging.cpp:210
void DisconnectTestLogger()
Only for testing.
Definition: logging.cpp:90
std::list< std::function< void(conststd::string &)> >::iterator PushBackCallback(std::function< void(const std::string &)> fun)
Connect a slot to the print signal and return the connection.
Definition: logging.h:139
std::list< std::string > m_msgs_before_open GUARDED_BY(m_cs)
std::atomic< uint32_t > m_categories
Log categories bitfield.
Definition: logging.h:102
bool DefaultShrinkDebugFile() const
Default for whether ShrinkDebugFile should be run.
Definition: logging.cpp:412
bool m_log_sourcelocations
Definition: logging.h:117
fs::path m_file_path
Definition: logging.h:119
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:259
bool m_log_time_micros
Definition: logging.h:115
bool m_log_threadnames
Definition: logging.h:116
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
std::vector< LogCategory > LogCategoriesList() const
Returns a vector of the log categories in alphabetical order.
Definition: logging.cpp:193
void DisableCategory(LogFlags category)
Definition: logging.cpp:387
void EnableCategory(LogFlags category)
Definition: logging.cpp:374
bool StartLogging()
Start logging (and flush all buffered messages)
Definition: logging.cpp:45
bool m_log_timestamps
Definition: logging.h:114
std::atomic< bool > m_reopen_file
Definition: logging.h:120
void ShrinkDebugFile()
Definition: logging.cpp:335
bool m_print_to_file
Definition: logging.h:112
uint32_t GetCategoryMask() const
Definition: logging.h:159
bool m_print_to_console
Definition: logging.h:111
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:108
StdMutex m_cs
Definition: logging.h:86
std::string LogCategoriesString() const
Returns a string with the log categories in alphabetical order.
Definition: logging.h:172
void DeleteCallback(std::list< std::function< void(const std::string &)> >::iterator it)
Delete a connection.
Definition: logging.h:146
Path class wrapper to block calls to the fs::path(std::string) implicit constructor and the fs::path:...
Definition: fs.h:30
bool error(const char *fmt, const Args &...args)
Definition: logging.h:263
static const bool DEFAULT_LOGTIMESTAMPS
Definition: logging.h:24
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:204
static const bool DEFAULT_LOGIPS
Definition: logging.h:23
static const bool DEFAULT_LOGTHREADNAMES
Definition: logging.h:25
static bool LogAcceptCategory(BCLog::LogFlags category, BCLog::Level level)
Return true if log accepts specified category, at the specified level.
Definition: logging.h:186
BCLog::Logger & LogInstance()
Definition: logging.cpp:21
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:158
static const bool DEFAULT_LOGSOURCELOCATIONS
Definition: logging.h:26
bool fLogIPs
Definition: logging.cpp:18
static const bool DEFAULT_LOGTIMEMICROS
Definition: logging.h:22
const char *const DEFAULT_DEBUGLOGFILE
Definition: logging.cpp:19
#define LogPrintf(...)
Definition: logging.h:227
Level
Definition: logging.h:74
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
@ TXPACKAGES
Definition: logging.h:70
@ WALLETDB
Definition: logging.h:46
@ ADDRMAN
Definition: logging.h:49
@ ALL
Definition: logging.h:71
@ 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:63
bool active
Definition: logging.h:33
std::string category
Definition: logging.h:32
#define LOCK(cs)
Definition: sync.h:306