Bitcoin Core 28.0.0
P2P Digital Currency
Loading...
Searching...
No Matches
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#include <util/time.h>
14
15#include <atomic>
16#include <cstdint>
17#include <functional>
18#include <list>
19#include <mutex>
20#include <string>
21#include <unordered_map>
22#include <vector>
23
24static const bool DEFAULT_LOGTIMEMICROS = false;
25static const bool DEFAULT_LOGIPS = false;
26static const bool DEFAULT_LOGTIMESTAMPS = true;
27static const bool DEFAULT_LOGTHREADNAMES = false;
28static const bool DEFAULT_LOGSOURCELOCATIONS = false;
29static constexpr bool DEFAULT_LOGLEVELALWAYS = false;
30extern const char * const DEFAULT_DEBUGLOGFILE;
31
32extern bool fLogIPs;
33
35 std::string category;
36 bool active;
37};
38
39namespace BCLog {
40 enum LogFlags : uint32_t {
41 NONE = 0,
42 NET = (1 << 0),
43 TOR = (1 << 1),
44 MEMPOOL = (1 << 2),
45 HTTP = (1 << 3),
46 BENCH = (1 << 4),
47 ZMQ = (1 << 5),
48 WALLETDB = (1 << 6),
49 RPC = (1 << 7),
50 ESTIMATEFEE = (1 << 8),
51 ADDRMAN = (1 << 9),
52 SELECTCOINS = (1 << 10),
53 REINDEX = (1 << 11),
54 CMPCTBLOCK = (1 << 12),
55 RAND = (1 << 13),
56 PRUNE = (1 << 14),
57 PROXY = (1 << 15),
58 MEMPOOLREJ = (1 << 16),
59 LIBEVENT = (1 << 17),
60 COINDB = (1 << 18),
61 QT = (1 << 19),
62 LEVELDB = (1 << 20),
63 VALIDATION = (1 << 21),
64 I2P = (1 << 22),
65 IPC = (1 << 23),
66#ifdef DEBUG_LOCKCONTENTION
67 LOCK = (1 << 24),
68#endif
69 BLOCKSTORAGE = (1 << 25),
70 TXRECONCILIATION = (1 << 26),
71 SCAN = (1 << 27),
72 TXPACKAGES = (1 << 28),
73 ALL = ~(uint32_t)0,
74 };
75 enum class Level {
76 Trace = 0, // High-volume or detailed logging for development/debugging
77 Debug, // Reasonably noisy logging, but still usable in production
78 Info, // Default
79 Warning,
80 Error,
81 };
83 constexpr size_t DEFAULT_MAX_LOG_BUFFER{1'000'000}; // buffer up to 1MB of log data prior to StartLogging
84
85 class Logger
86 {
87 public:
88 struct BufferedLog {
89 SystemClock::time_point now;
90 std::chrono::seconds mocktime;
95 };
96
97 private:
98 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
99
100 FILE* m_fileout GUARDED_BY(m_cs) = nullptr;
101 std::list<BufferedLog> m_msgs_before_open GUARDED_BY(m_cs);
102 bool m_buffering GUARDED_BY(m_cs) = true;
103 size_t m_max_buffer_memusage GUARDED_BY(m_cs){DEFAULT_MAX_LOG_BUFFER};
104 size_t m_cur_buffer_memusage GUARDED_BY(m_cs){0};
105 size_t m_buffer_lines_discarded GUARDED_BY(m_cs){0};
106
112 std::atomic_bool m_started_new_line{true};
113
115 std::unordered_map<LogFlags, Level> m_category_log_levels GUARDED_BY(m_cs);
116
119 std::atomic<Level> m_log_level{DEFAULT_LOG_LEVEL};
120
122 std::atomic<uint32_t> m_categories{BCLog::NONE};
123
124 void FormatLogStrInPlace(std::string& str, LogFlags category, Level level, std::string_view source_file, int source_line, std::string_view logging_function, std::string_view threadname, SystemClock::time_point now, std::chrono::seconds mocktime) const;
125
126 std::string LogTimestampStr(SystemClock::time_point now, std::chrono::seconds mocktime) const;
127
129 std::list<std::function<void(const std::string&)>> m_print_callbacks GUARDED_BY(m_cs) {};
130
132 void LogPrintStr_(std::string_view str, std::string_view logging_function, std::string_view source_file, int source_line, BCLog::LogFlags category, BCLog::Level level)
134
135 std::string GetLogPrefix(LogFlags category, Level level) const;
136
137 public:
138 bool m_print_to_console = false;
139 bool m_print_to_file = false;
140
146
148 std::atomic<bool> m_reopen_file{false};
149
151 void LogPrintStr(std::string_view str, std::string_view logging_function, std::string_view source_file, int source_line, BCLog::LogFlags category, BCLog::Level level)
153
156 {
157 StdLockGuard scoped_lock(m_cs);
158 return m_buffering || m_print_to_console || m_print_to_file || !m_print_callbacks.empty();
159 }
160
162 std::list<std::function<void(const std::string&)>>::iterator PushBackCallback(std::function<void(const std::string&)> fun) EXCLUSIVE_LOCKS_REQUIRED(!m_cs)
163 {
164 StdLockGuard scoped_lock(m_cs);
165 m_print_callbacks.push_back(std::move(fun));
166 return --m_print_callbacks.end();
167 }
168
170 void DeleteCallback(std::list<std::function<void(const std::string&)>>::iterator it) EXCLUSIVE_LOCKS_REQUIRED(!m_cs)
171 {
172 StdLockGuard scoped_lock(m_cs);
173 m_print_callbacks.erase(it);
174 }
175
180
188
189 void ShrinkDebugFile();
190
192 {
193 StdLockGuard scoped_lock(m_cs);
194 return m_category_log_levels;
195 }
196 void SetCategoryLogLevel(const std::unordered_map<LogFlags, Level>& levels) EXCLUSIVE_LOCKS_REQUIRED(!m_cs)
197 {
198 StdLockGuard scoped_lock(m_cs);
199 m_category_log_levels = levels;
200 }
201 bool SetCategoryLogLevel(std::string_view category_str, std::string_view level_str) EXCLUSIVE_LOCKS_REQUIRED(!m_cs);
202
203 Level LogLevel() const { return m_log_level.load(); }
204 void SetLogLevel(Level level) { m_log_level = level; }
205 bool SetLogLevel(std::string_view level);
206
207 uint32_t GetCategoryMask() const { return m_categories.load(); }
208
209 void EnableCategory(LogFlags flag);
210 bool EnableCategory(std::string_view str);
211 void DisableCategory(LogFlags flag);
212 bool DisableCategory(std::string_view str);
213
214 bool WillLogCategory(LogFlags category) const;
216
218 std::vector<LogCategory> LogCategoriesList() const;
220 std::string LogCategoriesString() const
221 {
222 return util::Join(LogCategoriesList(), ", ", [&](const LogCategory& i) { return i.category; });
223 };
224
226 std::string LogLevelsString() const;
227
229 static std::string LogLevelToStr(BCLog::Level level);
230
231 bool DefaultShrinkDebugFile() const;
232 };
233
234} // namespace BCLog
235
237
239static inline bool LogAcceptCategory(BCLog::LogFlags category, BCLog::Level level)
240{
241 return LogInstance().WillLogCategoryLevel(category, level);
242}
243
245bool GetLogCategory(BCLog::LogFlags& flag, std::string_view str);
246
247// Be conservative when using functions that
248// unconditionally log to debug.log! It should not be the case that an inbound
249// peer can fill up a user's disk with debug.log entries.
250
251template <typename... Args>
252static inline void LogPrintf_(std::string_view logging_function, std::string_view source_file, const int source_line, const BCLog::LogFlags flag, const BCLog::Level level, const char* fmt, const Args&... args)
253{
254 if (LogInstance().Enabled()) {
255 std::string log_msg;
256 try {
257 log_msg = tfm::format(fmt, args...);
258 } catch (tinyformat::format_error& fmterr) {
259 /* Original format string will have newline so don't add one here */
260 log_msg = "Error \"" + std::string(fmterr.what()) + "\" while formatting log message: " + fmt;
261 }
262 LogInstance().LogPrintStr(log_msg, logging_function, source_file, source_line, flag, level);
263 }
264}
265
266#define LogPrintLevel_(category, level, ...) LogPrintf_(__func__, __FILE__, __LINE__, category, level, __VA_ARGS__)
267
268// Log unconditionally.
269#define LogInfo(...) LogPrintLevel_(BCLog::LogFlags::ALL, BCLog::Level::Info, __VA_ARGS__)
270#define LogWarning(...) LogPrintLevel_(BCLog::LogFlags::ALL, BCLog::Level::Warning, __VA_ARGS__)
271#define LogError(...) LogPrintLevel_(BCLog::LogFlags::ALL, BCLog::Level::Error, __VA_ARGS__)
272
273// Deprecated unconditional logging.
274#define LogPrintf(...) LogInfo(__VA_ARGS__)
275#define LogPrintfCategory(category, ...) LogPrintLevel_(category, BCLog::Level::Info, __VA_ARGS__)
276
277// Use a macro instead of a function for conditional logging to prevent
278// evaluating arguments when logging for the category is not enabled.
279
280// Log conditionally, prefixing the output with the passed category name and severity level.
281#define LogPrintLevel(category, level, ...) \
282 do { \
283 if (LogAcceptCategory((category), (level))) { \
284 LogPrintLevel_(category, level, __VA_ARGS__); \
285 } \
286 } while (0)
287
288// Log conditionally, prefixing the output with the passed category name.
289#define LogDebug(category, ...) LogPrintLevel(category, BCLog::Level::Debug, __VA_ARGS__)
290#define LogTrace(category, ...) LogPrintLevel(category, BCLog::Level::Trace, __VA_ARGS__)
291
292// Deprecated conditional logging
293#define LogPrint(category, ...) LogDebug(category, __VA_ARGS__)
294
295#endif // BITCOIN_LOGGING_H
ArgsManager & args
Definition bitcoind.cpp:270
static std::string LogLevelToStr(BCLog::Level level)
Returns the string representation of a log level.
Definition logging.cpp:230
bool m_always_print_category_level
Definition logging.h:145
size_t m_buffer_lines_discarded GUARDED_BY(m_cs)
Definition logging.h:105
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
Definition logging.cpp:147
std::list< BufferedLog > m_msgs_before_open GUARDED_BY(m_cs)
std::string LogTimestampStr(SystemClock::time_point now, std::chrono::seconds mocktime) const
Definition logging.cpp:296
std::atomic< uint32_t > m_categories
Log categories bitfield.
Definition logging.h:122
size_t m_cur_buffer_memusage GUARDED_BY(m_cs)
Definition logging.h:104
bool DefaultShrinkDebugFile() const
Definition logging.cpp:165
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:144
void SetCategoryLogLevel(const std::unordered_map< LogFlags, Level > &levels) EXCLUSIVE_LOCKS_REQUIRED(!m_cs)
Definition logging.h:196
void SetLogLevel(Level level)
Definition logging.h:204
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:119
Level LogLevel() const
Definition logging.h:203
bool WillLogCategoryLevel(LogFlags category, Level level) const EXCLUSIVE_LOCKS_REQUIRED(!m_cs)
Definition logging.cpp:152
fs::path m_file_path
Definition logging.h:147
bool m_log_time_micros
Definition logging.h:142
bool m_log_threadnames
Definition logging.h:143
std::list< std::function< void(conststd::string &)> >::iterator PushBackCallback(std::function< void(const std::string &)> fun) EXCLUSIVE_LOCKS_REQUIRED(!m_cs)
Connect a slot to the print signal and return the connection.
Definition logging.h:162
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:112
void DisableLogging() EXCLUSIVE_LOCKS_REQUIRED(!m_cs)
Disable logging This offers a slight speedup and slightly smaller memory usage compared to leaving th...
Definition logging.cpp:109
std::vector< LogCategory > LogCategoriesList() const
Returns a vector of the log categories in alphabetical order.
Definition logging.cpp:274
bool StartLogging() EXCLUSIVE_LOCKS_REQUIRED(!m_cs)
Start logging (and flush all buffered messages)
Definition logging.cpp:51
void EnableCategory(LogFlags flag)
Definition logging.cpp:121
size_t m_max_buffer_memusage GUARDED_BY(m_cs)
Definition logging.h:103
void FormatLogStrInPlace(std::string &str, LogFlags category, Level level, std::string_view source_file, int source_line, std::string_view logging_function, std::string_view threadname, SystemClock::time_point now, std::chrono::seconds mocktime) const
Definition logging.cpp:370
bool m_log_timestamps
Definition logging.h:141
void DeleteCallback(std::list< std::function< void(const std::string &)> >::iterator it) EXCLUSIVE_LOCKS_REQUIRED(!m_cs)
Delete a connection.
Definition logging.h:170
std::string GetLogPrefix(LogFlags category, Level level) const
Definition logging.cpp:339
void LogPrintStr(std::string_view str, std::string_view logging_function, std::string_view source_file, int source_line, BCLog::LogFlags category, BCLog::Level level) EXCLUSIVE_LOCKS_REQUIRED(!m_cs)
Send a string to the log output.
Definition logging.cpp:385
void DisconnectTestLogger() EXCLUSIVE_LOCKS_REQUIRED(!m_cs)
Only for testing.
Definition logging.cpp:95
std::string LogLevelsString() const
Returns a string with all user-selectable log levels.
Definition logging.cpp:290
std::atomic< bool > m_reopen_file
Definition logging.h:148
void ShrinkDebugFile()
Definition logging.cpp:468
bool m_print_to_file
Definition logging.h:139
uint32_t GetCategoryMask() const
Definition logging.h:207
std::unordered_map< LogFlags, Level > CategoryLevels() const EXCLUSIVE_LOCKS_REQUIRED(!m_cs)
Definition logging.h:191
bool m_print_to_console
Definition logging.h:138
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:129
StdMutex m_cs
Definition logging.h:98
bool Enabled() const EXCLUSIVE_LOCKS_REQUIRED(!m_cs)
Returns whether logs will be written to any output.
Definition logging.h:155
std::string LogCategoriesString() const
Returns a string with the log categories in alphabetical order.
Definition logging.h:220
void DisableCategory(LogFlags flag)
Definition logging.cpp:134
void LogPrintStr_(std::string_view str, std::string_view logging_function, std::string_view source_file, int source_line, BCLog::LogFlags category, BCLog::Level level) EXCLUSIVE_LOCKS_REQUIRED(m_cs)
Send a string to the log output (internal)
Definition logging.cpp:391
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:26
bool GetLogCategory(BCLog::LogFlags &flag, std::string_view str)
Return true if str parses as a log category and set the flag.
Definition logging.cpp:216
static const bool DEFAULT_LOGIPS
Definition logging.h:25
static const bool DEFAULT_LOGTHREADNAMES
Definition logging.h:27
static bool LogAcceptCategory(BCLog::LogFlags category, BCLog::Level level)
Return true if log accepts specified category, at the specified level.
Definition logging.h:239
BCLog::Logger & LogInstance()
Definition logging.cpp:23
static const bool DEFAULT_LOGSOURCELOCATIONS
Definition logging.h:28
bool fLogIPs
Definition logging.cpp:44
static const bool DEFAULT_LOGTIMEMICROS
Definition logging.h:24
const char *const DEFAULT_DEBUGLOGFILE
Definition logging.cpp:20
static void LogPrintf_(std::string_view logging_function, std::string_view source_file, const int source_line, const BCLog::LogFlags flag, const BCLog::Level level, const char *fmt, const Args &... args)
Definition logging.h:252
static constexpr bool DEFAULT_LOGLEVELALWAYS
Definition logging.h:29
Level
Definition logging.h:75
constexpr size_t DEFAULT_MAX_LOG_BUFFER
Definition logging.h:83
LogFlags
Definition logging.h:40
@ ESTIMATEFEE
Definition logging.h:50
@ TXRECONCILIATION
Definition logging.h:70
@ RAND
Definition logging.h:55
@ BLOCKSTORAGE
Definition logging.h:69
@ COINDB
Definition logging.h:60
@ REINDEX
Definition logging.h:53
@ TXPACKAGES
Definition logging.h:72
@ WALLETDB
Definition logging.h:48
@ SCAN
Definition logging.h:71
@ ADDRMAN
Definition logging.h:51
@ ALL
Definition logging.h:73
@ RPC
Definition logging.h:49
@ HTTP
Definition logging.h:45
@ LEVELDB
Definition logging.h:62
@ NONE
Definition logging.h:41
@ VALIDATION
Definition logging.h:63
@ MEMPOOLREJ
Definition logging.h:58
@ PRUNE
Definition logging.h:56
@ TOR
Definition logging.h:43
@ LIBEVENT
Definition logging.h:59
@ CMPCTBLOCK
Definition logging.h:54
@ PROXY
Definition logging.h:57
@ ZMQ
Definition logging.h:47
@ IPC
Definition logging.h:65
@ MEMPOOL
Definition logging.h:44
@ SELECTCOINS
Definition logging.h:52
@ I2P
Definition logging.h:64
@ BENCH
Definition logging.h:46
@ NET
Definition logging.h:42
@ QT
Definition logging.h:61
constexpr auto DEFAULT_LOG_LEVEL
Definition logging.h:82
void format(std::ostream &out, const char *fmt, const Args &... args)
Format list of arguments to the stream according to given format string.
auto Join(const C &container, const S &separator, UnaryOp unary_op)
Join all container items.
Definition string.h:115
std::chrono::seconds mocktime
Definition logging.h:90
std::string source_file
Definition logging.h:91
SystemClock::time_point now
Definition logging.h:89
std::string logging_function
Definition logging.h:91
bool active
Definition logging.h:36
std::string category
Definition logging.h:35
#define LOCK(cs)
Definition sync.h:257
#define EXCLUSIVE_LOCKS_REQUIRED(...)