6#ifndef BITCOIN_LOGGING_H
7#define BITCOIN_LOGGING_H
24#include <source_location>
26#include <unordered_map>
27#include <unordered_set>
48 std::source_location loc = std::source_location::current())
52 std::uint_least32_t
line()
const {
return m_loc.line(); }
63 return lhs.line() == rhs.line() && std::string_view(lhs.file_name()) == std::string_view(rhs.file_name());
111#ifdef DEBUG_LOCKCONTENTION
154 std::unordered_map<SourceLocation, Stats, SourceLocationHasher, SourceLocationEqual> m_source_locations
GUARDED_BY(
m_mutex);
157 LogRateLimiter(uint64_t max_bytes, std::chrono::seconds reset_window);
160 using SchedulerFunction = std::function<void(std::function<
void()>, std::chrono::milliseconds)>;
169 static std::shared_ptr<LogRateLimiter>
Create(
172 std::chrono::seconds reset_window);
198 SystemClock::time_point
now;
231 std::string
LogTimestampStr(SystemClock::time_point now, std::chrono::seconds mocktime)
const;
234 std::list<std::function<void(
const std::string&)>> m_print_callbacks
GUARDED_BY(
m_cs) {};
270 m_print_callbacks.push_back(std::move(fun));
271 return --m_print_callbacks.end();
278 m_print_callbacks.erase(it);
284 return m_print_callbacks.size();
295 m_limiter = std::move(limiter);
311 return m_category_log_levels;
316 m_category_log_levels = levels;
321 m_category_log_levels[category] = level;
369template <
typename... Args>
377 log_msg =
"Error \"" + std::string{fmterr.what()} +
"\" while formatting log message: " + fmt.fmt;
385#define LogPrintLevel_(category, level, should_ratelimit, ...) LogPrintFormatInternal(SourceLocation{__func__}, category, level, should_ratelimit, __VA_ARGS__)
391#define LogInfo(...) LogPrintLevel_(BCLog::LogFlags::ALL, BCLog::Level::Info, true, __VA_ARGS__)
392#define LogWarning(...) LogPrintLevel_(BCLog::LogFlags::ALL, BCLog::Level::Warning, true, __VA_ARGS__)
393#define LogError(...) LogPrintLevel_(BCLog::LogFlags::ALL, BCLog::Level::Error, true, __VA_ARGS__)
401#define detail_LogIfCategoryAndLevelEnabled(category, level, ...) \
403 if (LogAcceptCategory((category), (level))) { \
404 bool rate_limit{level >= BCLog::Level::Info}; \
405 Assume(!rate_limit); \
406 LogPrintLevel_(category, level, rate_limit, __VA_ARGS__); \
411#define LogDebug(category, ...) detail_LogIfCategoryAndLevelEnabled(category, BCLog::Level::Debug, __VA_ARGS__)
412#define LogTrace(category, ...) detail_LogIfCategoryAndLevelEnabled(category, BCLog::Level::Trace, __VA_ARGS__)
Fixed window rate limiter for logging.
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 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...
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.
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.
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
std::list< BufferedLog > m_msgs_before_open GUARDED_BY(m_cs)
std::atomic< CategoryMask > m_categories
Log categories bitfield.
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
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)
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 DisconnectTestLogger() EXCLUSIVE_LOCKS_REQUIRED(!m_cs)
Only for testing.
void AddCategoryLogLevel(LogFlags category, Level level)
std::string LogLevelsString() const
Returns a string with all user-selectable log levels.
std::atomic< bool > m_reopen_file
std::unordered_map< LogFlags, Level > CategoryLevels() const EXCLUSIVE_LOCKS_REQUIRED(!m_cs)
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.
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)
General SipHash-2-4 implementation.
CSipHasher & Write(uint64_t data)
Hash a 64-bit integer worth of data.
Like std::source_location, but allowing to override the function name.
SourceLocation(const char *func, std::source_location loc=std::source_location::current())
The func argument must be constructed from the C++11 func macro.
std::string_view function_name_short() const
std::source_location m_loc
std::string_view file_name() const
std::uint_least32_t line() const
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
void LogPrintFormatInternal(SourceLocation &&source_loc, BCLog::LogFlags flag, BCLog::Level level, bool should_ratelimit, util::ConstevalFormatString< sizeof...(Args)> fmt, const Args &... args)
static const bool DEFAULT_LOGTIMEMICROS
const char *const DEFAULT_DEBUGLOGFILE
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
SystemClock::time_point now
SourceLocation source_loc
bool operator()(const SourceLocation &lhs, const SourceLocation &rhs) const noexcept
size_t operator()(const SourceLocation &s) const noexcept
#define EXCLUSIVE_LOCKS_REQUIRED(...)