6#ifndef BITCOIN_LOGGING_H
7#define BITCOIN_LOGGING_H
23#include <source_location>
25#include <unordered_map>
26#include <unordered_set>
40 bool operator()(
const std::source_location& lhs,
const std::source_location& rhs)
const noexcept
42 return lhs.line() == rhs.line() && std::string_view(lhs.file_name()) == std::string_view(rhs.file_name());
47 size_t operator()(
const std::source_location&
s)
const noexcept
90#ifdef DEBUG_LOCKCONTENTION
132 std::unordered_map<std::source_location, Stats, SourceLocationHasher, SourceLocationEqual> m_source_locations
GUARDED_BY(
m_mutex);
135 LogRateLimiter(uint64_t max_bytes, std::chrono::seconds reset_window);
138 using SchedulerFunction = std::function<void(std::function<
void()>, std::chrono::milliseconds)>;
147 static std::shared_ptr<LogRateLimiter>
Create(
150 std::chrono::seconds reset_window);
164 const std::source_location& source_loc,
176 SystemClock::time_point
now;
207 void FormatLogStrInPlace(std::string& str,
LogFlags category,
Level level,
const std::source_location& source_loc, std::string_view threadname, SystemClock::time_point now, std::chrono::seconds mocktime)
const;
209 std::string
LogTimestampStr(SystemClock::time_point now, std::chrono::seconds mocktime)
const;
212 std::list<std::function<void(
const std::string&)>> m_print_callbacks
GUARDED_BY(
m_cs) {};
248 m_print_callbacks.push_back(std::move(fun));
249 return --m_print_callbacks.end();
256 m_print_callbacks.erase(it);
267 m_limiter = std::move(limiter);
283 return m_category_log_levels;
288 m_category_log_levels = levels;
336template <
typename... Args>
344 log_msg =
"Error \"" + std::string{fmterr.what()} +
"\" while formatting log message: " + fmt.fmt;
350#define LogPrintLevel_(category, level, should_ratelimit, ...) LogPrintFormatInternal(std::source_location::current(), category, level, should_ratelimit, __VA_ARGS__)
356#define LogInfo(...) LogPrintLevel_(BCLog::LogFlags::ALL, BCLog::Level::Info, true, __VA_ARGS__)
357#define LogWarning(...) LogPrintLevel_(BCLog::LogFlags::ALL, BCLog::Level::Warning, true, __VA_ARGS__)
358#define LogError(...) LogPrintLevel_(BCLog::LogFlags::ALL, BCLog::Level::Error, true, __VA_ARGS__)
361#define LogPrintf(...) LogInfo(__VA_ARGS__)
372#define LogPrintLevel(category, level, ...) \
374 if (LogAcceptCategory((category), (level))) { \
375 bool rate_limit{level >= BCLog::Level::Info}; \
376 LogPrintLevel_(category, level, rate_limit, __VA_ARGS__); \
381#define LogDebug(category, ...) LogPrintLevel(category, BCLog::Level::Debug, __VA_ARGS__)
382#define LogTrace(category, ...) LogPrintLevel(category, BCLog::Level::Trace, __VA_ARGS__)
Fixed window rate limiter for logging.
std::unordered_map< std::source_location, Stats, SourceLocationHasher, SourceLocationEqual > m_source_locations GUARDED_BY(m_mutex)
Stats for each source location that has attempted to log something.
static std::shared_ptr< LogRateLimiter > Create(SchedulerFunction &&scheduler_func, uint64_t max_bytes, std::chrono::seconds reset_window)
std::function< void(std::function< void()>, std::chrono::milliseconds)> SchedulerFunction
const uint64_t m_max_bytes
Maximum number of bytes logged per location per window.
LogRateLimiter(uint64_t max_bytes, std::chrono::seconds reset_window)
Status Consume(const std::source_location &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...
bool SuppressionsActive() const
Returns true if any log locations are currently being suppressed.
const std::chrono::seconds m_reset_window
Interval after which the window is reset.
Status
Suppression status of a source log location.
void Reset() EXCLUSIVE_LOCKS_REQUIRED(!m_mutex)
Resets all usage to zero. Called periodically by the scheduler.
std::atomic< bool > m_suppression_active
Whether any log locations are suppressed. Cached view on m_source_locations for performance reasons.
static std::string LogLevelToStr(BCLog::Level level)
Returns the string representation of a log level.
bool m_always_print_category_level
size_t m_buffer_lines_discarded GUARDED_BY(m_cs)
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
void LogPrintStr(std::string_view str, std::source_location &&source_loc, BCLog::LogFlags category, BCLog::Level level, bool should_ratelimit) EXCLUSIVE_LOCKS_REQUIRED(!m_cs)
Send a string to the log output.
std::list< BufferedLog > m_msgs_before_open GUARDED_BY(m_cs)
std::atomic< CategoryMask > m_categories
Log categories bitfield.
std::string LogTimestampStr(SystemClock::time_point now, std::chrono::seconds mocktime) const
size_t m_cur_buffer_memusage GUARDED_BY(m_cs)
bool DefaultShrinkDebugFile() const
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
void SetCategoryLogLevel(const std::unordered_map< LogFlags, Level > &levels) EXCLUSIVE_LOCKS_REQUIRED(!m_cs)
void SetLogLevel(Level level)
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...
CategoryMask GetCategoryMask() const
bool WillLogCategoryLevel(LogFlags category, Level level) const EXCLUSIVE_LOCKS_REQUIRED(!m_cs)
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.
void SetRateLimiting(std::shared_ptr< LogRateLimiter > limiter) EXCLUSIVE_LOCKS_REQUIRED(!m_cs)
void DisableLogging() EXCLUSIVE_LOCKS_REQUIRED(!m_cs)
Disable logging This offers a slight speedup and slightly smaller memory usage compared to leaving th...
std::vector< LogCategory > LogCategoriesList() const
Returns a vector of the log categories in alphabetical order.
bool StartLogging() EXCLUSIVE_LOCKS_REQUIRED(!m_cs)
Start logging (and flush all buffered messages)
void EnableCategory(LogFlags flag)
size_t m_max_buffer_memusage GUARDED_BY(m_cs)
void DeleteCallback(std::list< std::function< void(const std::string &)> >::iterator it) EXCLUSIVE_LOCKS_REQUIRED(!m_cs)
Delete a connection.
std::string GetLogPrefix(LogFlags category, Level level) const
void LogPrintStr_(std::string_view str, std::source_location &&source_loc, BCLog::LogFlags category, BCLog::Level level, bool should_ratelimit) EXCLUSIVE_LOCKS_REQUIRED(m_cs)
Send a string to the log output (internal)
void DisconnectTestLogger() EXCLUSIVE_LOCKS_REQUIRED(!m_cs)
Only for testing.
std::string LogLevelsString() const
Returns a string with all user-selectable log levels.
std::atomic< bool > m_reopen_file
void FormatLogStrInPlace(std::string &str, LogFlags category, Level level, const std::source_location &source_loc, std::string_view threadname, SystemClock::time_point now, std::chrono::seconds mocktime) const
std::unordered_map< LogFlags, Level > CategoryLevels() const EXCLUSIVE_LOCKS_REQUIRED(!m_cs)
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.
bool Enabled() const EXCLUSIVE_LOCKS_REQUIRED(!m_cs)
Returns whether logs will be written to any output.
std::string LogCategoriesString() const
Returns a string with the log categories in alphabetical order.
void DisableCategory(LogFlags flag)
CSipHasher & Write(uint64_t data)
Hash a 64-bit integer worth of data It is treated as if this was the little-endian interpretation of ...
static const bool DEFAULT_LOGTIMESTAMPS
bool GetLogCategory(BCLog::LogFlags &flag, std::string_view str)
Return true if str parses as a log category and set the flag.
static const bool DEFAULT_LOGIPS
static const bool DEFAULT_LOGTHREADNAMES
static bool LogAcceptCategory(BCLog::LogFlags category, BCLog::Level level)
Return true if log accepts specified category, at the specified level.
BCLog::Logger & LogInstance()
static const bool DEFAULT_LOGSOURCELOCATIONS
static const bool DEFAULT_LOGTIMEMICROS
const char *const DEFAULT_DEBUGLOGFILE
void LogPrintFormatInternal(std::source_location &&source_loc, BCLog::LogFlags flag, BCLog::Level level, bool should_ratelimit, util::ConstevalFormatString< sizeof...(Args)> fmt, const Args &... args)
static constexpr bool DEFAULT_LOGLEVELALWAYS
constexpr auto RATELIMIT_WINDOW
constexpr bool DEFAULT_LOGRATELIMIT
constexpr uint64_t RATELIMIT_MAX_BYTES
constexpr size_t DEFAULT_MAX_LOG_BUFFER
constexpr auto DEFAULT_LOG_LEVEL
auto Join(const C &container, const S &separator, UnaryOp unary_op)
Join all container items.
constexpr auto MakeUCharSpan(const V &v) -> decltype(UCharSpanCast(std::span{v}))
Like the std::span constructor, but for (const) unsigned char member types only.
Keeps track of an individual source location and how many available bytes are left for logging from i...
uint64_t m_available_bytes
Remaining bytes.
Stats(uint64_t max_bytes)
bool Consume(uint64_t bytes)
Updates internal accounting and returns true if enough available_bytes were remaining.
uint64_t m_dropped_bytes
Number of bytes that were consumed but didn't fit in the available bytes.
std::chrono::seconds mocktime
std::source_location source_loc
SystemClock::time_point now
bool operator()(const std::source_location &lhs, const std::source_location &rhs) const noexcept
size_t operator()(const std::source_location &s) const noexcept
#define EXCLUSIVE_LOCKS_REQUIRED(...)