Bitcoin Core 28.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-present 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 using CategoryMask = uint64_t;
43 NET = (CategoryMask{1} << 0),
44 TOR = (CategoryMask{1} << 1),
45 MEMPOOL = (CategoryMask{1} << 2),
46 HTTP = (CategoryMask{1} << 3),
47 BENCH = (CategoryMask{1} << 4),
48 ZMQ = (CategoryMask{1} << 5),
50 RPC = (CategoryMask{1} << 7),
52 ADDRMAN = (CategoryMask{1} << 9),
54 REINDEX = (CategoryMask{1} << 11),
56 RAND = (CategoryMask{1} << 13),
57 PRUNE = (CategoryMask{1} << 14),
58 PROXY = (CategoryMask{1} << 15),
60 LIBEVENT = (CategoryMask{1} << 17),
61 COINDB = (CategoryMask{1} << 18),
62 QT = (CategoryMask{1} << 19),
63 LEVELDB = (CategoryMask{1} << 20),
65 I2P = (CategoryMask{1} << 22),
66 IPC = (CategoryMask{1} << 23),
67#ifdef DEBUG_LOCKCONTENTION
68 LOCK = (CategoryMask{1} << 24),
69#endif
72 SCAN = (CategoryMask{1} << 27),
75 };
76 enum class Level {
77 Trace = 0, // High-volume or detailed logging for development/debugging
78 Debug, // Reasonably noisy logging, but still usable in production
79 Info, // Default
80 Warning,
81 Error,
82 };
84 constexpr size_t DEFAULT_MAX_LOG_BUFFER{1'000'000}; // buffer up to 1MB of log data prior to StartLogging
85
86 class Logger
87 {
88 public:
89 struct BufferedLog {
90 SystemClock::time_point now;
91 std::chrono::seconds mocktime;
96 };
97
98 private:
99 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
100
101 FILE* m_fileout GUARDED_BY(m_cs) = nullptr;
102 std::list<BufferedLog> m_msgs_before_open GUARDED_BY(m_cs);
103 bool m_buffering GUARDED_BY(m_cs) = true;
104 size_t m_max_buffer_memusage GUARDED_BY(m_cs){DEFAULT_MAX_LOG_BUFFER};
105 size_t m_cur_buffer_memusage GUARDED_BY(m_cs){0};
106 size_t m_buffer_lines_discarded GUARDED_BY(m_cs){0};
107
109 std::unordered_map<LogFlags, Level> m_category_log_levels GUARDED_BY(m_cs);
110
113 std::atomic<Level> m_log_level{DEFAULT_LOG_LEVEL};
114
116 std::atomic<CategoryMask> m_categories{BCLog::NONE};
117
118 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;
119
120 std::string LogTimestampStr(SystemClock::time_point now, std::chrono::seconds mocktime) const;
121
123 std::list<std::function<void(const std::string&)>> m_print_callbacks GUARDED_BY(m_cs) {};
124
126 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)
128
129 std::string GetLogPrefix(LogFlags category, Level level) const;
130
131 public:
132 bool m_print_to_console = false;
133 bool m_print_to_file = false;
134
140
142 std::atomic<bool> m_reopen_file{false};
143
145 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)
147
150 {
151 StdLockGuard scoped_lock(m_cs);
152 return m_buffering || m_print_to_console || m_print_to_file || !m_print_callbacks.empty();
153 }
154
156 std::list<std::function<void(const std::string&)>>::iterator PushBackCallback(std::function<void(const std::string&)> fun) EXCLUSIVE_LOCKS_REQUIRED(!m_cs)
157 {
158 StdLockGuard scoped_lock(m_cs);
159 m_print_callbacks.push_back(std::move(fun));
160 return --m_print_callbacks.end();
161 }
162
164 void DeleteCallback(std::list<std::function<void(const std::string&)>>::iterator it) EXCLUSIVE_LOCKS_REQUIRED(!m_cs)
165 {
166 StdLockGuard scoped_lock(m_cs);
167 m_print_callbacks.erase(it);
168 }
169
174
182
183 void ShrinkDebugFile();
184
186 {
187 StdLockGuard scoped_lock(m_cs);
188 return m_category_log_levels;
189 }
190 void SetCategoryLogLevel(const std::unordered_map<LogFlags, Level>& levels) EXCLUSIVE_LOCKS_REQUIRED(!m_cs)
191 {
192 StdLockGuard scoped_lock(m_cs);
193 m_category_log_levels = levels;
194 }
195 bool SetCategoryLogLevel(std::string_view category_str, std::string_view level_str) EXCLUSIVE_LOCKS_REQUIRED(!m_cs);
196
197 Level LogLevel() const { return m_log_level.load(); }
198 void SetLogLevel(Level level) { m_log_level = level; }
199 bool SetLogLevel(std::string_view level);
200
201 CategoryMask GetCategoryMask() const { return m_categories.load(); }
202
203 void EnableCategory(LogFlags flag);
204 bool EnableCategory(std::string_view str);
205 void DisableCategory(LogFlags flag);
206 bool DisableCategory(std::string_view str);
207
208 bool WillLogCategory(LogFlags category) const;
210
212 std::vector<LogCategory> LogCategoriesList() const;
214 std::string LogCategoriesString() const
215 {
216 return util::Join(LogCategoriesList(), ", ", [&](const LogCategory& i) { return i.category; });
217 };
218
220 std::string LogLevelsString() const;
221
223 static std::string LogLevelToStr(BCLog::Level level);
224
225 bool DefaultShrinkDebugFile() const;
226 };
227
228} // namespace BCLog
229
231
233static inline bool LogAcceptCategory(BCLog::LogFlags category, BCLog::Level level)
234{
235 return LogInstance().WillLogCategoryLevel(category, level);
236}
237
239bool GetLogCategory(BCLog::LogFlags& flag, std::string_view str);
240
241template <typename... Args>
242inline void LogPrintFormatInternal(std::string_view logging_function, std::string_view source_file, const int source_line, const BCLog::LogFlags flag, const BCLog::Level level, util::ConstevalFormatString<sizeof...(Args)> fmt, const Args&... args)
243{
244 if (LogInstance().Enabled()) {
245 std::string log_msg;
246 try {
247 log_msg = tfm::format(fmt, args...);
248 } catch (tinyformat::format_error& fmterr) {
249 log_msg = "Error \"" + std::string{fmterr.what()} + "\" while formatting log message: " + fmt.fmt;
250 }
251 LogInstance().LogPrintStr(log_msg, logging_function, source_file, source_line, flag, level);
252 }
253}
254
255#define LogPrintLevel_(category, level, ...) LogPrintFormatInternal(__func__, __FILE__, __LINE__, category, level, __VA_ARGS__)
256
257// Log unconditionally.
258// Be conservative when using functions that unconditionally log to debug.log!
259// It should not be the case that an inbound peer can fill up a user's storage
260// with debug.log entries.
261#define LogInfo(...) LogPrintLevel_(BCLog::LogFlags::ALL, BCLog::Level::Info, __VA_ARGS__)
262#define LogWarning(...) LogPrintLevel_(BCLog::LogFlags::ALL, BCLog::Level::Warning, __VA_ARGS__)
263#define LogError(...) LogPrintLevel_(BCLog::LogFlags::ALL, BCLog::Level::Error, __VA_ARGS__)
264
265// Deprecated unconditional logging.
266#define LogPrintf(...) LogInfo(__VA_ARGS__)
267
268// Use a macro instead of a function for conditional logging to prevent
269// evaluating arguments when logging for the category is not enabled.
270
271// Log conditionally, prefixing the output with the passed category name and severity level.
272#define LogPrintLevel(category, level, ...) \
273 do { \
274 if (LogAcceptCategory((category), (level))) { \
275 LogPrintLevel_(category, level, __VA_ARGS__); \
276 } \
277 } while (0)
278
279// Log conditionally, prefixing the output with the passed category name.
280#define LogDebug(category, ...) LogPrintLevel(category, BCLog::Level::Debug, __VA_ARGS__)
281#define LogTrace(category, ...) LogPrintLevel(category, BCLog::Level::Trace, __VA_ARGS__)
282
283#endif // BITCOIN_LOGGING_H
ArgsManager & args
Definition: bitcoind.cpp:277
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:139
size_t m_buffer_lines_discarded GUARDED_BY(m_cs)
Definition: logging.h:106
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::atomic< CategoryMask > m_categories
Log categories bitfield.
Definition: logging.h:116
std::string LogTimestampStr(SystemClock::time_point now, std::chrono::seconds mocktime) const
Definition: logging.cpp:296
size_t m_cur_buffer_memusage GUARDED_BY(m_cs)
Definition: logging.h:105
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:138
void SetCategoryLogLevel(const std::unordered_map< LogFlags, Level > &levels) EXCLUSIVE_LOCKS_REQUIRED(!m_cs)
Definition: logging.h:190
void SetLogLevel(Level level)
Definition: logging.h:198
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:113
Level LogLevel() const
Definition: logging.h:197
CategoryMask GetCategoryMask() const
Definition: logging.h:201
bool WillLogCategoryLevel(LogFlags category, Level level) const EXCLUSIVE_LOCKS_REQUIRED(!m_cs)
Definition: logging.cpp:152
fs::path m_file_path
Definition: logging.h:141
bool m_log_time_micros
Definition: logging.h:136
bool m_log_threadnames
Definition: logging.h:137
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:156
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:52
void EnableCategory(LogFlags flag)
Definition: logging.cpp:121
size_t m_max_buffer_memusage GUARDED_BY(m_cs)
Definition: logging.h:104
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:135
void DeleteCallback(std::list< std::function< void(const std::string &)> >::iterator it) EXCLUSIVE_LOCKS_REQUIRED(!m_cs)
Delete a connection.
Definition: logging.h:164
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:387
void DisconnectTestLogger() EXCLUSIVE_LOCKS_REQUIRED(!m_cs)
Only for testing.
Definition: logging.cpp:96
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:142
void ShrinkDebugFile()
Definition: logging.cpp:454
bool m_print_to_file
Definition: logging.h:133
std::unordered_map< LogFlags, Level > CategoryLevels() const EXCLUSIVE_LOCKS_REQUIRED(!m_cs)
Definition: logging.h:185
bool m_print_to_console
Definition: logging.h:132
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:123
StdMutex m_cs
Definition: logging.h:99
bool Enabled() const EXCLUSIVE_LOCKS_REQUIRED(!m_cs)
Returns whether logs will be written to any output.
Definition: logging.h:149
std::string LogCategoriesString() const
Returns a string with the log categories in alphabetical order.
Definition: logging.h:214
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:393
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
void LogPrintFormatInternal(std::string_view logging_function, std::string_view source_file, const int source_line, const BCLog::LogFlags flag, const BCLog::Level level, util::ConstevalFormatString< sizeof...(Args)> fmt, const Args &... args)
Definition: logging.h:242
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:233
BCLog::Logger & LogInstance()
Definition: logging.cpp:24
static const bool DEFAULT_LOGSOURCELOCATIONS
Definition: logging.h:28
bool fLogIPs
Definition: logging.cpp:45
static const bool DEFAULT_LOGTIMEMICROS
Definition: logging.h:24
const char *const DEFAULT_DEBUGLOGFILE
Definition: logging.cpp:21
static constexpr bool DEFAULT_LOGLEVELALWAYS
Definition: logging.h:29
Level
Definition: logging.h:76
constexpr size_t DEFAULT_MAX_LOG_BUFFER
Definition: logging.h:84
uint64_t CategoryMask
Definition: logging.h:40
constexpr auto DEFAULT_LOG_LEVEL
Definition: logging.h:83
LogFlags
Definition: logging.h:41
@ ESTIMATEFEE
Definition: logging.h:51
@ TXRECONCILIATION
Definition: logging.h:71
@ RAND
Definition: logging.h:56
@ BLOCKSTORAGE
Definition: logging.h:70
@ COINDB
Definition: logging.h:61
@ REINDEX
Definition: logging.h:54
@ TXPACKAGES
Definition: logging.h:73
@ WALLETDB
Definition: logging.h:49
@ SCAN
Definition: logging.h:72
@ ADDRMAN
Definition: logging.h:52
@ ALL
Definition: logging.h:74
@ RPC
Definition: logging.h:50
@ HTTP
Definition: logging.h:46
@ LEVELDB
Definition: logging.h:63
@ NONE
Definition: logging.h:42
@ VALIDATION
Definition: logging.h:64
@ MEMPOOLREJ
Definition: logging.h:59
@ PRUNE
Definition: logging.h:57
@ TOR
Definition: logging.h:44
@ LIBEVENT
Definition: logging.h:60
@ CMPCTBLOCK
Definition: logging.h:55
@ PROXY
Definition: logging.h:58
@ ZMQ
Definition: logging.h:48
@ IPC
Definition: logging.h:66
@ MEMPOOL
Definition: logging.h:45
@ SELECTCOINS
Definition: logging.h:53
@ I2P
Definition: logging.h:65
@ BENCH
Definition: logging.h:47
@ NET
Definition: logging.h:43
@ QT
Definition: logging.h:62
void format(std::ostream &out, FormatStringCheck< sizeof...(Args)> fmt, const Args &... args)
Format list of arguments to the stream according to given format string.
Definition: tinyformat.h:1072
auto Join(const C &container, const S &separator, UnaryOp unary_op)
Join all container items.
Definition: string.h:192
std::chrono::seconds mocktime
Definition: logging.h:91
std::string threadname
Definition: logging.h:92
std::string source_file
Definition: logging.h:92
SystemClock::time_point now
Definition: logging.h:90
std::string logging_function
Definition: logging.h:92
bool active
Definition: logging.h:36
std::string category
Definition: logging.h:35
A wrapper for a compile-time partially validated format string.
Definition: string.h:92
#define LOCK(cs)
Definition: sync.h:257
#define EXCLUSIVE_LOCKS_REQUIRED(...)
Definition: threadsafety.h:49