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/byte_units.h>
13#include <util/fs.h>
14#include <util/log.h> // IWYU pragma: export
15#include <util/stdmutex.h>
16#include <util/string.h>
17#include <util/time.h>
18
19#include <atomic>
20#include <cstdint>
21#include <cstring>
22#include <functional>
23#include <list>
24#include <memory>
25#include <optional>
26#include <string>
27#include <unordered_map>
28#include <vector>
29
30static const bool DEFAULT_LOGTIMEMICROS = false;
31static const bool DEFAULT_LOGIPS = false;
32static const bool DEFAULT_LOGTIMESTAMPS = true;
33static const bool DEFAULT_LOGTHREADNAMES = false;
34static const bool DEFAULT_LOGSOURCELOCATIONS = false;
35static constexpr bool DEFAULT_LOGLEVELALWAYS = false;
36extern const char * const DEFAULT_DEBUGLOGFILE;
37
38extern bool fLogIPs;
39
41 bool operator()(const SourceLocation& lhs, const SourceLocation& rhs) const noexcept
42 {
43 return lhs.line() == rhs.line() && std::string_view(lhs.file_name()) == std::string_view(rhs.file_name());
44 }
45};
46
48 size_t operator()(const SourceLocation& s) const noexcept
49 {
50 // Use CSipHasher(0, 0) as a simple way to get uniform distribution.
51 return size_t(CSipHasher(0, 0)
52 .Write(s.line())
53 .Write(MakeUCharSpan(std::string_view{s.file_name()}))
54 .Finalize());
55 }
56};
57
59 std::string category;
60 bool active;
61};
62
63namespace BCLog {
64 constexpr auto DEFAULT_LOG_LEVEL{Level::Debug};
65 constexpr size_t DEFAULT_MAX_LOG_BUFFER{1'000'000}; // buffer up to 1MB of log data prior to StartLogging
66 constexpr uint64_t RATELIMIT_MAX_BYTES{1_MiB}; // maximum number of bytes per source location that can be logged within the RATELIMIT_WINDOW
67 constexpr auto RATELIMIT_WINDOW{1h}; // time window after which log ratelimit stats are reset
68 constexpr bool DEFAULT_LOGRATELIMIT{true};
69
72 {
73 public:
75 struct Stats {
79 uint64_t m_dropped_bytes{0};
80
81 Stats(uint64_t max_bytes) : m_available_bytes{max_bytes} {}
83 bool Consume(uint64_t bytes);
84 };
85
86 private:
88
90 std::unordered_map<SourceLocation, Stats, SourceLocationHasher, SourceLocationEqual> m_source_locations GUARDED_BY(m_mutex);
92 std::atomic<bool> m_suppression_active{false};
93 LogRateLimiter(uint64_t max_bytes, std::chrono::seconds reset_window);
94
95 public:
96 using SchedulerFunction = std::function<void(std::function<void()>, std::chrono::milliseconds)>;
105 static std::shared_ptr<LogRateLimiter> Create(
106 SchedulerFunction&& scheduler_func,
107 uint64_t max_bytes,
108 std::chrono::seconds reset_window);
110 const uint64_t m_max_bytes;
112 const std::chrono::seconds m_reset_window;
114 enum class Status {
115 UNSUPPRESSED, // string fits within the limit
116 NEWLY_SUPPRESSED, // suppression has started since this string
117 STILL_SUPPRESSED, // suppression is still ongoing
118 };
121 [[nodiscard]] Status Consume(
122 const SourceLocation& source_loc,
123 const std::string& str) EXCLUSIVE_LOCKS_REQUIRED(!m_mutex);
128 };
129
130 class Logger
131 {
132 private:
133 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
134
135 FILE* m_fileout GUARDED_BY(m_cs) = nullptr;
136 std::list<util::log::Entry> m_msgs_before_open GUARDED_BY(m_cs);
137 bool m_buffering GUARDED_BY(m_cs) = true;
138 size_t m_max_buffer_memusage GUARDED_BY(m_cs){DEFAULT_MAX_LOG_BUFFER};
139 size_t m_cur_buffer_memusage GUARDED_BY(m_cs){0};
140 size_t m_buffer_lines_discarded GUARDED_BY(m_cs){0};
141
143 std::shared_ptr<LogRateLimiter> m_limiter GUARDED_BY(m_cs);
144
146 std::unordered_map<LogFlags, Level> m_category_log_levels GUARDED_BY(m_cs);
147
150 std::atomic<Level> m_log_level{DEFAULT_LOG_LEVEL};
151
153 std::atomic<CategoryMask> m_categories{BCLog::NONE};
154
155 std::string Format(const util::log::Entry& entry) const;
156
157 std::string LogTimestampStr(SystemClock::time_point now, std::chrono::seconds mocktime) const;
158
160 std::list<std::function<void(const std::string&)>> m_print_callbacks GUARDED_BY(m_cs){};
161
164
165 std::string GetLogPrefix(LogFlags category, Level level) const;
166
167 public:
168 bool m_print_to_console = false;
169 bool m_print_to_file = false;
170
176
177 fs::path m_file_path;
178 std::atomic<bool> m_reopen_file{false};
179
182
185 {
186 STDLOCK(m_cs);
187 return m_buffering || m_print_to_console || m_print_to_file || !m_print_callbacks.empty();
188 }
189
191 std::list<std::function<void(const std::string&)>>::iterator PushBackCallback(std::function<void(const std::string&)> fun) EXCLUSIVE_LOCKS_REQUIRED(!m_cs)
192 {
193 STDLOCK(m_cs);
194 m_print_callbacks.push_back(std::move(fun));
195 return --m_print_callbacks.end();
196 }
197
199 void DeleteCallback(std::list<std::function<void(const std::string&)>>::iterator it) EXCLUSIVE_LOCKS_REQUIRED(!m_cs)
200 {
201 STDLOCK(m_cs);
202 m_print_callbacks.erase(it);
203 }
204
206 {
207 STDLOCK(m_cs);
208 return m_print_callbacks.size();
209 }
210
215
217 {
218 STDLOCK(m_cs);
219 m_limiter = std::move(limiter);
220 }
221
229
230 void ShrinkDebugFile();
231
233 {
234 STDLOCK(m_cs);
235 return m_category_log_levels;
236 }
237 void SetCategoryLogLevel(const std::unordered_map<LogFlags, Level>& levels) EXCLUSIVE_LOCKS_REQUIRED(!m_cs)
238 {
239 STDLOCK(m_cs);
240 m_category_log_levels = levels;
241 }
243 {
244 STDLOCK(m_cs);
245 m_category_log_levels[category] = level;
246 }
247 bool SetCategoryLogLevel(std::string_view category_str, std::string_view level_str) EXCLUSIVE_LOCKS_REQUIRED(!m_cs);
248
249 Level LogLevel() const { return m_log_level.load(); }
250 void SetLogLevel(Level level) { m_log_level = level; }
251 bool SetLogLevel(std::string_view level);
252
253 CategoryMask GetCategoryMask() const { return m_categories.load(); }
254
255 void EnableCategory(LogFlags flag);
256 bool EnableCategory(std::string_view str);
257 void DisableCategory(LogFlags flag);
258 bool DisableCategory(std::string_view str);
259
260 bool WillLogCategory(LogFlags category) const;
262
264 std::vector<LogCategory> LogCategoriesList() const;
266 std::string LogCategoriesString() const
267 {
268 return util::Join(LogCategoriesList(), ", ", [&](const LogCategory& i) { return i.category; });
269 };
270
272 std::string LogLevelsString() const;
273
275 static std::string LogLevelToStr(BCLog::Level level);
276
277 bool DefaultShrinkDebugFile() const;
278 };
279
280} // namespace BCLog
281
283
285static inline bool LogAcceptCategory(BCLog::LogFlags category, BCLog::Level level)
286{
287 return LogInstance().WillLogCategoryLevel(category, level);
288}
289
291std::optional<BCLog::LogFlags> GetLogCategory(std::string_view str);
292
293#endif // BITCOIN_LOGGING_H
Fixed window rate limiter for logging.
Definition: logging.h:72
static std::shared_ptr< LogRateLimiter > Create(SchedulerFunction &&scheduler_func, uint64_t max_bytes, std::chrono::seconds reset_window)
Definition: logging.cpp:384
std::function< void(std::function< void()>, std::chrono::milliseconds)> SchedulerFunction
Definition: logging.h:96
const uint64_t m_max_bytes
Maximum number of bytes logged per location per window.
Definition: logging.h:110
LogRateLimiter(uint64_t max_bytes, std::chrono::seconds reset_window)
Definition: logging.cpp:381
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:396
StdMutex m_mutex
Definition: logging.h:87
bool SuppressionsActive() const
Returns true if any log locations are currently being suppressed.
Definition: logging.h:127
const std::chrono::seconds m_reset_window
Interval after which the window is reset.
Definition: logging.h:112
Status
Suppression status of a source log location.
Definition: logging.h:114
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:556
std::atomic< bool > m_suppression_active
Whether any log locations are suppressed. Cached view on m_source_locations for performance reasons.
Definition: logging.h:92
static std::string LogLevelToStr(BCLog::Level level)
Returns the string representation of a log level.
Definition: logging.cpp:239
bool m_always_print_category_level
Definition: logging.h:175
size_t m_buffer_lines_discarded GUARDED_BY(m_cs)
Definition: logging.h:140
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:156
std::atomic< CategoryMask > m_categories
Log categories bitfield.
Definition: logging.h:153
std::string LogTimestampStr(SystemClock::time_point now, std::chrono::seconds mocktime) const
Definition: logging.cpp:305
size_t m_cur_buffer_memusage GUARDED_BY(m_cs)
Definition: logging.h:139
bool DefaultShrinkDebugFile() const
Definition: logging.cpp:174
std::unordered_map< LogFlags, Level > m_category_log_levels GUARDED_BY(m_cs)
Category-specific log level. Overrides m_log_level.
void LogPrint_(util::log::Entry log_entry) EXCLUSIVE_LOCKS_REQUIRED(m_cs)
Send an entry to the log output (internal)
Definition: logging.cpp:438
bool m_log_sourcelocations
Definition: logging.h:174
void SetCategoryLogLevel(const std::unordered_map< LogFlags, Level > &levels) EXCLUSIVE_LOCKS_REQUIRED(!m_cs)
Definition: logging.h:237
void SetLogLevel(Level level)
Definition: logging.h:250
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:150
Level LogLevel() const
Definition: logging.h:249
CategoryMask GetCategoryMask() const
Definition: logging.h:253
size_t NumConnections() EXCLUSIVE_LOCKS_REQUIRED(!m_cs)
Definition: logging.h:205
bool WillLogCategoryLevel(LogFlags category, Level level) const EXCLUSIVE_LOCKS_REQUIRED(!m_cs)
Definition: logging.cpp:161
fs::path m_file_path
Definition: logging.h:177
bool m_log_time_micros
Definition: logging.h:172
bool m_log_threadnames
Definition: logging.h:173
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:191
void SetRateLimiting(std::shared_ptr< LogRateLimiter > limiter) EXCLUSIVE_LOCKS_REQUIRED(!m_cs)
Definition: logging.h:216
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:116
std::vector< LogCategory > LogCategoriesList() const
Returns a vector of the log categories in alphabetical order.
Definition: logging.cpp:283
bool StartLogging() EXCLUSIVE_LOCKS_REQUIRED(!m_cs)
Start logging (and flush all buffered messages)
Definition: logging.cpp:54
std::list< util::log::Entry > m_msgs_before_open GUARDED_BY(m_cs)
void EnableCategory(LogFlags flag)
Definition: logging.cpp:128
size_t m_max_buffer_memusage GUARDED_BY(m_cs)
Definition: logging.h:138
void AddCategoryLogLevel(LogFlags category, Level level) EXCLUSIVE_LOCKS_REQUIRED(!m_cs)
Definition: logging.h:242
bool m_log_timestamps
Definition: logging.h:171
void DeleteCallback(std::list< std::function< void(const std::string &)> >::iterator it) EXCLUSIVE_LOCKS_REQUIRED(!m_cs)
Delete a connection.
Definition: logging.h:199
std::string GetLogPrefix(LogFlags category, Level level) const
Definition: logging.cpp:348
void DisconnectTestLogger() EXCLUSIVE_LOCKS_REQUIRED(!m_cs)
Only for testing.
Definition: logging.cpp:103
std::string LogLevelsString() const
Returns a string with all user-selectable log levels.
Definition: logging.cpp:299
std::atomic< bool > m_reopen_file
Definition: logging.h:178
void LogPrint(util::log::Entry log_entry) EXCLUSIVE_LOCKS_REQUIRED(!m_cs)
Send an entry to the log output.
Definition: logging.cpp:431
void ShrinkDebugFile()
Definition: logging.cpp:515
bool m_print_to_file
Definition: logging.h:169
std::unordered_map< LogFlags, Level > CategoryLevels() const EXCLUSIVE_LOCKS_REQUIRED(!m_cs)
Definition: logging.h:232
bool m_print_to_console
Definition: logging.h:168
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:160
StdMutex m_cs
Definition: logging.h:133
std::string Format(const util::log::Entry &entry) const
Definition: logging.cpp:412
bool Enabled() const EXCLUSIVE_LOCKS_REQUIRED(!m_cs)
Returns whether logs will be written to any output.
Definition: logging.h:184
std::string LogCategoriesString() const
Returns a string with the log categories in alphabetical order.
Definition: logging.h:266
void DisableCategory(LogFlags flag)
Definition: logging.cpp:142
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:23
static const bool DEFAULT_LOGTIMESTAMPS
Definition: logging.h:32
static const bool DEFAULT_LOGIPS
Definition: logging.h:31
static const bool DEFAULT_LOGTHREADNAMES
Definition: logging.h:33
static bool LogAcceptCategory(BCLog::LogFlags category, BCLog::Level level)
Return true if log accepts specified category, at the specified level.
Definition: logging.h:285
BCLog::Logger & LogInstance()
Definition: logging.cpp:26
static const bool DEFAULT_LOGSOURCELOCATIONS
Definition: logging.h:34
bool fLogIPs
Definition: logging.cpp:47
static const bool DEFAULT_LOGTIMEMICROS
Definition: logging.h:30
const char *const DEFAULT_DEBUGLOGFILE
Definition: logging.cpp:23
static constexpr bool DEFAULT_LOGLEVELALWAYS
Definition: logging.h:35
std::optional< BCLog::LogFlags > GetLogCategory(std::string_view str)
Return log flag if str parses as a log category.
Definition: logging.cpp:227
constexpr auto RATELIMIT_WINDOW
Definition: logging.h:67
constexpr bool DEFAULT_LOGRATELIMIT
Definition: logging.h:68
constexpr uint64_t RATELIMIT_MAX_BYTES
Definition: logging.h:66
constexpr size_t DEFAULT_MAX_LOG_BUFFER
Definition: logging.h:65
uint64_t CategoryMask
Definition: categories.h:12
constexpr auto DEFAULT_LOG_LEVEL
Definition: logging.h:64
LogFlags
Definition: categories.h:14
@ NONE
Definition: categories.h:15
Definition: common.h:30
Level
Definition: log.h:46
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:75
uint64_t m_available_bytes
Remaining bytes.
Definition: logging.h:77
Stats(uint64_t max_bytes)
Definition: logging.h:81
bool Consume(uint64_t bytes)
Updates internal accounting and returns true if enough available_bytes were remaining.
Definition: logging.cpp:574
uint64_t m_dropped_bytes
Number of bytes that were consumed but didn't fit in the available bytes.
Definition: logging.h:79
bool active
Definition: logging.h:60
std::string category
Definition: logging.h:59
bool operator()(const SourceLocation &lhs, const SourceLocation &rhs) const noexcept
Definition: logging.h:41
size_t operator()(const SourceLocation &s) const noexcept
Definition: logging.h:48
Definition: log.h:54
#define EXCLUSIVE_LOCKS_REQUIRED(...)
Definition: threadsafety.h:49