Bitcoin Core 31.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 <crypto/siphash.h>
10#include <logging/categories.h> // IWYU pragma: export
11#include <span.h>
12#include <util/fs.h>
13#include <util/log.h> // IWYU pragma: export
14#include <util/stdmutex.h>
15#include <util/string.h>
16#include <util/time.h>
17
18#include <atomic>
19#include <cstdint>
20#include <cstring>
21#include <functional>
22#include <list>
23#include <memory>
24#include <optional>
25#include <string>
26#include <unordered_map>
27#include <vector>
28
29static const bool DEFAULT_LOGTIMEMICROS = false;
30static const bool DEFAULT_LOGIPS = false;
31static const bool DEFAULT_LOGTIMESTAMPS = true;
32static const bool DEFAULT_LOGTHREADNAMES = false;
33static const bool DEFAULT_LOGSOURCELOCATIONS = false;
34static constexpr bool DEFAULT_LOGLEVELALWAYS = false;
35extern const char * const DEFAULT_DEBUGLOGFILE;
36
37extern bool fLogIPs;
38
40 bool operator()(const SourceLocation& lhs, const SourceLocation& rhs) const noexcept
41 {
42 return lhs.line() == rhs.line() && std::string_view(lhs.file_name()) == std::string_view(rhs.file_name());
43 }
44};
45
47 size_t operator()(const SourceLocation& s) const noexcept
48 {
49 // Use CSipHasher(0, 0) as a simple way to get uniform distribution.
50 return size_t(CSipHasher(0, 0)
51 .Write(s.line())
52 .Write(MakeUCharSpan(std::string_view{s.file_name()}))
53 .Finalize());
54 }
55};
56
58 std::string category;
59 bool active;
60};
61
62namespace BCLog {
63 constexpr auto DEFAULT_LOG_LEVEL{Level::Debug};
64 constexpr size_t DEFAULT_MAX_LOG_BUFFER{1'000'000}; // buffer up to 1MB of log data prior to StartLogging
65 constexpr uint64_t RATELIMIT_MAX_BYTES{1024 * 1024}; // maximum number of bytes per source location that can be logged within the RATELIMIT_WINDOW
66 constexpr auto RATELIMIT_WINDOW{1h}; // time window after which log ratelimit stats are reset
67 constexpr bool DEFAULT_LOGRATELIMIT{true};
68
71 {
72 public:
74 struct Stats {
78 uint64_t m_dropped_bytes{0};
79
80 Stats(uint64_t max_bytes) : m_available_bytes{max_bytes} {}
82 bool Consume(uint64_t bytes);
83 };
84
85 private:
87
89 std::unordered_map<SourceLocation, Stats, SourceLocationHasher, SourceLocationEqual> m_source_locations GUARDED_BY(m_mutex);
91 std::atomic<bool> m_suppression_active{false};
92 LogRateLimiter(uint64_t max_bytes, std::chrono::seconds reset_window);
93
94 public:
95 using SchedulerFunction = std::function<void(std::function<void()>, std::chrono::milliseconds)>;
104 static std::shared_ptr<LogRateLimiter> Create(
105 SchedulerFunction&& scheduler_func,
106 uint64_t max_bytes,
107 std::chrono::seconds reset_window);
109 const uint64_t m_max_bytes;
111 const std::chrono::seconds m_reset_window;
113 enum class Status {
114 UNSUPPRESSED, // string fits within the limit
115 NEWLY_SUPPRESSED, // suppression has started since this string
116 STILL_SUPPRESSED, // suppression is still ongoing
117 };
120 [[nodiscard]] Status Consume(
121 const SourceLocation& source_loc,
122 const std::string& str) EXCLUSIVE_LOCKS_REQUIRED(!m_mutex);
127 };
128
129 class Logger
130 {
131 public:
132 struct BufferedLog {
133 SystemClock::time_point now;
134 std::chrono::seconds mocktime;
135 std::string str, threadname;
139 };
140
141 private:
142 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
143
144 FILE* m_fileout GUARDED_BY(m_cs) = nullptr;
145 std::list<BufferedLog> m_msgs_before_open GUARDED_BY(m_cs);
146 bool m_buffering GUARDED_BY(m_cs) = true;
147 size_t m_max_buffer_memusage GUARDED_BY(m_cs){DEFAULT_MAX_LOG_BUFFER};
148 size_t m_cur_buffer_memusage GUARDED_BY(m_cs){0};
149 size_t m_buffer_lines_discarded GUARDED_BY(m_cs){0};
150
152 std::shared_ptr<LogRateLimiter> m_limiter GUARDED_BY(m_cs);
153
155 std::unordered_map<LogFlags, Level> m_category_log_levels GUARDED_BY(m_cs);
156
159 std::atomic<Level> m_log_level{DEFAULT_LOG_LEVEL};
160
162 std::atomic<CategoryMask> m_categories{BCLog::NONE};
163
164 void FormatLogStrInPlace(std::string& str, LogFlags category, Level level, const SourceLocation& source_loc, std::string_view threadname, SystemClock::time_point now, std::chrono::seconds mocktime) const;
165
166 std::string LogTimestampStr(SystemClock::time_point now, std::chrono::seconds mocktime) const;
167
169 std::list<std::function<void(const std::string&)>> m_print_callbacks GUARDED_BY(m_cs) {};
170
172 void LogPrintStr_(std::string_view str, SourceLocation&& source_loc, BCLog::LogFlags category, BCLog::Level level, bool should_ratelimit)
174
175 std::string GetLogPrefix(LogFlags category, Level level) const;
176
177 public:
178 bool m_print_to_console = false;
179 bool m_print_to_file = false;
180
186
187 fs::path m_file_path;
188 std::atomic<bool> m_reopen_file{false};
189
191 void LogPrintStr(std::string_view str, SourceLocation&& source_loc, BCLog::LogFlags category, BCLog::Level level, bool should_ratelimit)
193
196 {
197 STDLOCK(m_cs);
198 return m_buffering || m_print_to_console || m_print_to_file || !m_print_callbacks.empty();
199 }
200
202 std::list<std::function<void(const std::string&)>>::iterator PushBackCallback(std::function<void(const std::string&)> fun) EXCLUSIVE_LOCKS_REQUIRED(!m_cs)
203 {
204 STDLOCK(m_cs);
205 m_print_callbacks.push_back(std::move(fun));
206 return --m_print_callbacks.end();
207 }
208
210 void DeleteCallback(std::list<std::function<void(const std::string&)>>::iterator it) EXCLUSIVE_LOCKS_REQUIRED(!m_cs)
211 {
212 STDLOCK(m_cs);
213 m_print_callbacks.erase(it);
214 }
215
217 {
218 STDLOCK(m_cs);
219 return m_print_callbacks.size();
220 }
221
226
228 {
229 STDLOCK(m_cs);
230 m_limiter = std::move(limiter);
231 }
232
240
241 void ShrinkDebugFile();
242
244 {
245 STDLOCK(m_cs);
246 return m_category_log_levels;
247 }
248 void SetCategoryLogLevel(const std::unordered_map<LogFlags, Level>& levels) EXCLUSIVE_LOCKS_REQUIRED(!m_cs)
249 {
250 STDLOCK(m_cs);
251 m_category_log_levels = levels;
252 }
254 {
255 STDLOCK(m_cs);
256 m_category_log_levels[category] = level;
257 }
258 bool SetCategoryLogLevel(std::string_view category_str, std::string_view level_str) EXCLUSIVE_LOCKS_REQUIRED(!m_cs);
259
260 Level LogLevel() const { return m_log_level.load(); }
261 void SetLogLevel(Level level) { m_log_level = level; }
262 bool SetLogLevel(std::string_view level);
263
264 CategoryMask GetCategoryMask() const { return m_categories.load(); }
265
266 void EnableCategory(LogFlags flag);
267 bool EnableCategory(std::string_view str);
268 void DisableCategory(LogFlags flag);
269 bool DisableCategory(std::string_view str);
270
271 bool WillLogCategory(LogFlags category) const;
273
275 std::vector<LogCategory> LogCategoriesList() const;
277 std::string LogCategoriesString() const
278 {
279 return util::Join(LogCategoriesList(), ", ", [&](const LogCategory& i) { return i.category; });
280 };
281
283 std::string LogLevelsString() const;
284
286 static std::string LogLevelToStr(BCLog::Level level);
287
288 bool DefaultShrinkDebugFile() const;
289 };
290
291} // namespace BCLog
292
294
296static inline bool LogAcceptCategory(BCLog::LogFlags category, BCLog::Level level)
297{
298 return LogInstance().WillLogCategoryLevel(category, level);
299}
300
302std::optional<BCLog::LogFlags> GetLogCategory(std::string_view str);
303
304#endif // BITCOIN_LOGGING_H
Fixed window rate limiter for logging.
Definition: logging.h:71
static std::shared_ptr< LogRateLimiter > Create(SchedulerFunction &&scheduler_func, uint64_t max_bytes, std::chrono::seconds reset_window)
Definition: logging.cpp:379
std::function< void(std::function< void()>, std::chrono::milliseconds)> SchedulerFunction
Definition: logging.h:95
const uint64_t m_max_bytes
Maximum number of bytes logged per location per window.
Definition: logging.h:109
LogRateLimiter(uint64_t max_bytes, std::chrono::seconds reset_window)
Definition: logging.cpp:376
Status Consume(const SourceLocation &source_loc, const std::string &str) EXCLUSIVE_LOCKS_REQUIRED(!m_mutex)
Consumes source_loc's available bytes corresponding to the size of the (formatted) str and returns it...
Definition: logging.cpp:391
StdMutex m_mutex
Definition: logging.h:86
bool SuppressionsActive() const
Returns true if any log locations are currently being suppressed.
Definition: logging.h:126
const std::chrono::seconds m_reset_window
Interval after which the window is reset.
Definition: logging.h:111
Status
Suppression status of a source log location.
Definition: logging.h:113
std::unordered_map< SourceLocation, Stats, SourceLocationHasher, SourceLocationEqual > m_source_locations GUARDED_BY(m_mutex)
Stats for each source location that has attempted to log something.
void Reset() EXCLUSIVE_LOCKS_REQUIRED(!m_mutex)
Resets all usage to zero. Called periodically by the scheduler.
Definition: logging.cpp:555
std::atomic< bool > m_suppression_active
Whether any log locations are suppressed. Cached view on m_source_locations for performance reasons.
Definition: logging.h:91
static std::string LogLevelToStr(BCLog::Level level)
Returns the string representation of a log level.
Definition: logging.cpp:234
bool m_always_print_category_level
Definition: logging.h:185
size_t m_buffer_lines_discarded GUARDED_BY(m_cs)
Definition: logging.h:149
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:151
std::list< BufferedLog > m_msgs_before_open GUARDED_BY(m_cs)
std::atomic< CategoryMask > m_categories
Log categories bitfield.
Definition: logging.h:162
void FormatLogStrInPlace(std::string &str, LogFlags category, Level level, const SourceLocation &source_loc, std::string_view threadname, SystemClock::time_point now, std::chrono::seconds mocktime) const
Definition: logging.cpp:407
void LogPrintStr_(std::string_view str, SourceLocation &&source_loc, BCLog::LogFlags category, BCLog::Level level, bool should_ratelimit) EXCLUSIVE_LOCKS_REQUIRED(m_cs)
Send a string to the log output (internal)
Definition: logging.cpp:431
std::string LogTimestampStr(SystemClock::time_point now, std::chrono::seconds mocktime) const
Definition: logging.cpp:300
size_t m_cur_buffer_memusage GUARDED_BY(m_cs)
Definition: logging.h:148
bool DefaultShrinkDebugFile() const
Definition: logging.cpp:169
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:184
void SetCategoryLogLevel(const std::unordered_map< LogFlags, Level > &levels) EXCLUSIVE_LOCKS_REQUIRED(!m_cs)
Definition: logging.h:248
void SetLogLevel(Level level)
Definition: logging.h:261
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:159
Level LogLevel() const
Definition: logging.h:260
CategoryMask GetCategoryMask() const
Definition: logging.h:264
size_t NumConnections() EXCLUSIVE_LOCKS_REQUIRED(!m_cs)
Definition: logging.h:216
bool WillLogCategoryLevel(LogFlags category, Level level) const EXCLUSIVE_LOCKS_REQUIRED(!m_cs)
Definition: logging.cpp:156
fs::path m_file_path
Definition: logging.h:187
bool m_log_time_micros
Definition: logging.h:182
bool m_log_threadnames
Definition: logging.h:183
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:202
void SetRateLimiting(std::shared_ptr< LogRateLimiter > limiter) EXCLUSIVE_LOCKS_REQUIRED(!m_cs)
Definition: logging.h:227
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:111
std::vector< LogCategory > LogCategoriesList() const
Returns a vector of the log categories in alphabetical order.
Definition: logging.cpp:278
bool StartLogging() EXCLUSIVE_LOCKS_REQUIRED(!m_cs)
Start logging (and flush all buffered messages)
Definition: logging.cpp:54
void EnableCategory(LogFlags flag)
Definition: logging.cpp:123
size_t m_max_buffer_memusage GUARDED_BY(m_cs)
Definition: logging.h:147
void AddCategoryLogLevel(LogFlags category, Level level) EXCLUSIVE_LOCKS_REQUIRED(!m_cs)
Definition: logging.h:253
bool m_log_timestamps
Definition: logging.h:181
void DeleteCallback(std::list< std::function< void(const std::string &)> >::iterator it) EXCLUSIVE_LOCKS_REQUIRED(!m_cs)
Delete a connection.
Definition: logging.h:210
std::string GetLogPrefix(LogFlags category, Level level) const
Definition: logging.cpp:343
void DisconnectTestLogger() EXCLUSIVE_LOCKS_REQUIRED(!m_cs)
Only for testing.
Definition: logging.cpp:98
std::string LogLevelsString() const
Returns a string with all user-selectable log levels.
Definition: logging.cpp:294
std::atomic< bool > m_reopen_file
Definition: logging.h:188
void ShrinkDebugFile()
Definition: logging.cpp:514
bool m_print_to_file
Definition: logging.h:179
std::unordered_map< LogFlags, Level > CategoryLevels() const EXCLUSIVE_LOCKS_REQUIRED(!m_cs)
Definition: logging.h:243
bool m_print_to_console
Definition: logging.h:178
void LogPrintStr(std::string_view str, SourceLocation &&source_loc, BCLog::LogFlags category, BCLog::Level level, bool should_ratelimit) EXCLUSIVE_LOCKS_REQUIRED(!m_cs)
Send a string to the log output.
Definition: logging.cpp:424
std::shared_ptr< LogRateLimiter > m_limiter GUARDED_BY(m_cs)
Manages the rate limiting of each log location.
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:169
StdMutex m_cs
Definition: logging.h:142
bool Enabled() const EXCLUSIVE_LOCKS_REQUIRED(!m_cs)
Returns whether logs will be written to any output.
Definition: logging.h:195
std::string LogCategoriesString() const
Returns a string with the log categories in alphabetical order.
Definition: logging.h:277
void DisableCategory(LogFlags flag)
Definition: logging.cpp:137
General SipHash-2-4 implementation.
Definition: siphash.h:27
CSipHasher & Write(uint64_t data)
Hash a 64-bit integer worth of data.
Definition: siphash.cpp:24
Like std::source_location, but allowing to override the function name.
Definition: log.h:21
static const bool DEFAULT_LOGTIMESTAMPS
Definition: logging.h:31
static const bool DEFAULT_LOGIPS
Definition: logging.h:30
static const bool DEFAULT_LOGTHREADNAMES
Definition: logging.h:32
static bool LogAcceptCategory(BCLog::LogFlags category, BCLog::Level level)
Return true if log accepts specified category, at the specified level.
Definition: logging.h:296
BCLog::Logger & LogInstance()
Definition: logging.cpp:26
static const bool DEFAULT_LOGSOURCELOCATIONS
Definition: logging.h:33
bool fLogIPs
Definition: logging.cpp:47
static const bool DEFAULT_LOGTIMEMICROS
Definition: logging.h:29
const char *const DEFAULT_DEBUGLOGFILE
Definition: logging.cpp:23
static constexpr bool DEFAULT_LOGLEVELALWAYS
Definition: logging.h:34
std::optional< BCLog::LogFlags > GetLogCategory(std::string_view str)
Return log flag if str parses as a log category.
Definition: logging.cpp:222
constexpr auto RATELIMIT_WINDOW
Definition: logging.h:66
constexpr bool DEFAULT_LOGRATELIMIT
Definition: logging.h:67
constexpr uint64_t RATELIMIT_MAX_BYTES
Definition: logging.h:65
constexpr size_t DEFAULT_MAX_LOG_BUFFER
Definition: logging.h:64
uint64_t CategoryMask
Definition: categories.h:12
constexpr auto DEFAULT_LOG_LEVEL
Definition: logging.h:63
LogFlags
Definition: categories.h:14
@ NONE
Definition: categories.h:15
Definition: common.h:29
Level
Definition: log.h:43
auto Join(const C &container, const S &separator, UnaryOp unary_op)
Join all container items.
Definition: string.h:206
constexpr auto MakeUCharSpan(const V &v) -> decltype(UCharSpanCast(std::span{v}))
Like the std::span constructor, but for (const) unsigned char member types only.
Definition: span.h:111
#define STDLOCK(cs)
Definition: stdmutex.h:41
Keeps track of an individual source location and how many available bytes are left for logging from i...
Definition: logging.h:74
uint64_t m_available_bytes
Remaining bytes.
Definition: logging.h:76
Stats(uint64_t max_bytes)
Definition: logging.h:80
bool Consume(uint64_t bytes)
Updates internal accounting and returns true if enough available_bytes were remaining.
Definition: logging.cpp:573
uint64_t m_dropped_bytes
Number of bytes that were consumed but didn't fit in the available bytes.
Definition: logging.h:78
std::chrono::seconds mocktime
Definition: logging.h:134
std::string threadname
Definition: logging.h:135
SystemClock::time_point now
Definition: logging.h:133
SourceLocation source_loc
Definition: logging.h:136
bool active
Definition: logging.h:59
std::string category
Definition: logging.h:58
bool operator()(const SourceLocation &lhs, const SourceLocation &rhs) const noexcept
Definition: logging.h:40
size_t operator()(const SourceLocation &s) const noexcept
Definition: logging.h:47
#define EXCLUSIVE_LOCKS_REQUIRED(...)
Definition: threadsafety.h:49