Bitcoin Core 32.99.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-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
30inline constexpr bool DEFAULT_LOGTIMEMICROS = false;
31inline constexpr bool DEFAULT_LOGIPS = false;
32inline constexpr bool DEFAULT_LOGTIMESTAMPS = true;
33inline constexpr bool DEFAULT_LOGTHREADNAMES = false;
34inline constexpr bool DEFAULT_LOGSOURCELOCATIONS = false;
35inline 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 inline constexpr auto DEFAULT_LOG_LEVEL{Level::Debug};
65 inline constexpr size_t DEFAULT_MAX_LOG_BUFFER{1'000'000}; // buffer up to 1MB of log data prior to StartLogging
66 inline constexpr uint64_t RATELIMIT_MAX_BYTES{1_MiB}; // maximum number of bytes per source location that can be logged within the RATELIMIT_WINDOW
67 inline constexpr auto RATELIMIT_WINDOW{1h}; // time window after which log ratelimit stats are reset
68 inline constexpr bool DEFAULT_LOGRATELIMIT{true};
69
72 {
73 public:
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(
108 std::chrono::seconds reset_window);
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 };
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
136 std::list<util::log::Entry> m_msgs_before_open GUARDED_BY(m_cs);
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
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
209
215
222
224
230 void SetCategoryLogLevel(const std::unordered_map<LogFlags, Level>& levels) EXCLUSIVE_LOCKS_REQUIRED(!m_cs)
231 {
232 STDLOCK(m_cs);
234 }
235 bool SetCategoryLogLevel(std::string_view category_str, std::string_view level_str) EXCLUSIVE_LOCKS_REQUIRED(!m_cs);
236
237 Level LogLevel() const { return m_log_level.load(); }
238 void SetLogLevel(Level level) { m_log_level = level; }
239 bool SetLogLevel(std::string_view level);
240
241 CategoryMask GetCategoryMask() const { return m_categories.load(); }
242
243 void EnableCategory(LogFlags flag);
244 bool EnableCategory(std::string_view str);
245 void DisableCategory(LogFlags flag);
246 bool DisableCategory(std::string_view str);
247
248 bool WillLogCategory(LogFlags category) const;
250
252 std::vector<LogCategory> LogCategoriesList() const;
254 std::string LogCategoriesString() const
255 {
256 return util::Join(LogCategoriesList(), ", ", [&](const LogCategory& i) { return i.category; });
257 };
258
260 std::string LogLevelsString() const;
261
263 static std::string LogLevelToStr(BCLog::Level level);
264
265 bool DefaultShrinkDebugFile() const;
266
268 static std::optional<BCLog::LogFlags> GetLogCategory(std::string_view str);
269 };
270} // namespace BCLog
271
273
274#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:390
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
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:402
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:571
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:244
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:157
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:310
size_t m_cur_buffer_memusage GUARDED_BY(m_cs)
Definition logging.h:139
bool DefaultShrinkDebugFile() const
Definition logging.cpp:175
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:444
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:230
void SetLogLevel(Level level)
Definition logging.h:238
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:237
void ShrinkDebugFile() EXCLUSIVE_LOCKS_REQUIRED(!m_cs)
Definition logging.cpp:521
CategoryMask GetCategoryMask() const
Definition logging.h:241
bool WillLogCategoryLevel(LogFlags category, Level level) const EXCLUSIVE_LOCKS_REQUIRED(!m_cs)
Definition logging.cpp:162
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:210
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:117
std::vector< LogCategory > LogCategoriesList() const
Returns a vector of the log categories in alphabetical order.
Definition logging.cpp:288
static std::optional< BCLog::LogFlags > GetLogCategory(std::string_view str)
Return log flag if str parses as a log category.
Definition logging.cpp:228
bool StartLogging() EXCLUSIVE_LOCKS_REQUIRED(!m_cs)
Start logging (and flush all buffered messages)
Definition logging.cpp:55
std::list< util::log::Entry > m_msgs_before_open GUARDED_BY(m_cs)
void EnableCategory(LogFlags flag)
Definition logging.cpp:129
size_t m_max_buffer_memusage GUARDED_BY(m_cs)
Definition logging.h:138
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:354
void DisconnectTestLogger() EXCLUSIVE_LOCKS_REQUIRED(!m_cs)
Only for testing.
Definition logging.cpp:104
std::string LogLevelsString() const
Returns a string with all user-selectable log levels.
Definition logging.cpp:304
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:437
bool m_print_to_file
Definition logging.h:169
std::unordered_map< LogFlags, Level > CategoryLevels() const EXCLUSIVE_LOCKS_REQUIRED(!m_cs)
Definition logging.h:225
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
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:254
void DisableCategory(LogFlags flag)
Definition logging.cpp:143
General SipHash-2-4 implementation.
Definition siphash.h:99
CSipHasher & Write(uint64_t data)
Hash a 64-bit integer worth of data.
Definition siphash.cpp:14
Like std::source_location, but allowing to override the function name.
Definition log.h:24
constexpr bool DEFAULT_LOGTIMESTAMPS
Definition logging.h:32
constexpr bool DEFAULT_LOGIPS
Definition logging.h:31
constexpr bool DEFAULT_LOGTIMEMICROS
Definition logging.h:30
BCLog::Logger & LogInstance()
Definition logging.cpp:27
bool fLogIPs
Definition logging.cpp:48
const char *const DEFAULT_DEBUGLOGFILE
Definition logging.cpp:24
constexpr bool DEFAULT_LOGSOURCELOCATIONS
Definition logging.h:34
constexpr bool DEFAULT_LOGLEVELALWAYS
Definition logging.h:35
constexpr bool DEFAULT_LOGTHREADNAMES
Definition logging.h:33
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
Level
Definition log.h:53
auto Join(const C &container, const S &separator, UnaryOp unary_op)
Join all container items.
Definition string.h:209
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:588
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:61
#define EXCLUSIVE_LOCKS_REQUIRED(...)
constexpr auto Ticks(Dur2 d)
Helper to count the seconds of a duration/time_point.
Definition time.h:82