7#ifndef BITCOIN_LOGGING_H
8#define BITCOIN_LOGGING_H
25#include <source_location>
27#include <unordered_map>
28#include <unordered_set>
43 const std::source_location &rhs)
const noexcept {
44 return lhs.line() == rhs.line() &&
45 std::string_view(lhs.file_name()) ==
46 std::string_view(rhs.file_name());
51 size_t operator()(
const std::source_location &s)
const noexcept {
94#ifdef DEBUG_LOCKCONTENTION
151 LogRateLimiter(uint64_t max_bytes, std::chrono::seconds reset_window);
155 std::function<void(std::function<
bool()>, std::chrono::milliseconds)>;
165 static std::shared_ptr<LogRateLimiter>
167 std::chrono::seconds reset_window);
183 [[nodiscard]]
Status Consume(
const std::source_location &source_loc,
184 const std::string &str)
195 SystemClock::time_point
now;
238 const std::source_location &source_loc,
239 std::string_view threadname,
240 SystemClock::time_point now,
241 std::chrono::seconds mocktime)
const;
244 std::chrono::seconds mocktime)
const;
247 std::list<std::function<void(
const std::string &)>>
251 void LogPrintStr_(std::string_view str, std::source_location &&source_loc,
273 void LogPrintStr(std::string_view str, std::source_location &&source_loc,
275 bool should_ratelimit);
281 !m_print_callbacks.empty();
285 std::list<std::function<void(
const std::string &)>>::iterator
289 m_print_callbacks.push_back(std::move(fun));
290 return --m_print_callbacks.end();
295 std::list<std::function<
void(
const std::string &)>>::iterator it)
298 m_print_callbacks.erase(it);
317 m_limiter = std::move(limiter);
325 return m_category_log_levels;
330 m_category_log_levels = levels;
333 std::string_view level_str)
386template <
typename... Args>
387static inline void LogPrintf_(std::source_location &&source_loc,
389 bool should_ratelimit,
const char *fmt,
390 const Args &...args) {
399 log_msg =
"Error \"" + std::string(fmterr.what()) +
400 "\" while formatting log message: " + fmt;
407#define LogPrintLevel_(category, level, should_ratelimit, ...) \
408 LogPrintf_(std::source_location::current(), category, level, \
409 should_ratelimit, __VA_ARGS__)
413#define LogInfo(...) \
414 LogPrintLevel_(BCLog::LogFlags::ALL, BCLog::Level::Info, \
416#define LogWarning(...) \
417 LogPrintLevel_(BCLog::LogFlags::ALL, BCLog::Level::Warning, \
419#define LogError(...) \
420 LogPrintLevel_(BCLog::LogFlags::ALL, BCLog::Level::Error, \
424#define LogPrintf(...) LogInfo(__VA_ARGS__)
437#define LogPrintLevel(category, level, ...) \
439 if (LogAcceptCategory((category), (level))) { \
440 bool rate_limit{level >= BCLog::Level::Info}; \
441 LogPrintLevel_(category, level, rate_limit, __VA_ARGS__); \
446#define LogDebug(category, ...) \
447 LogPrintLevel(category, BCLog::Level::Debug, __VA_ARGS__)
448#define LogTrace(category, ...) \
449 LogPrintLevel(category, BCLog::Level::Trace, __VA_ARGS__)
452#define LogPrint(category, ...) LogDebug(category, __VA_ARGS__)
459#define LogPrintfToBeContinued LogPrintf
460#define LogPrintToBeContinued LogPrint
461#define LogPrintLevelToBeContinued LogPrintLevel
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< bool()>, 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.
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.
void LogPrintStr(std::string_view str, std::source_location &&source_loc, BCLog::LogFlags category, BCLog::Level level, bool should_ratelimit)
Send a string to the log output.
bool WillLogCategory(LogFlags category) const
Return true if log accepts specified category.
std::list< BufferedLog > m_msgs_before_open GUARDED_BY(m_cs)
std::string LogTimestampStr(SystemClock::time_point now, std::chrono::seconds mocktime) const
std::atomic< uint32_t > m_categories
Log categories bitfield.
size_t m_cur_buffer_memusage GUARDED_BY(m_cs)
bool DefaultShrinkDebugFile() const
Default for whether ShrinkDebugFile should be run.
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...
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.
std::atomic_bool m_started_new_line
m_started_new_line is a state variable that will suppress printing of the timestamp when multiple cal...
void SetRateLimiting(std::shared_ptr< LogRateLimiter > limiter) EXCLUSIVE_LOCKS_REQUIRED(!m_cs)
void DisableLogging() EXCLUSIVE_LOCKS_REQUIRED(!m_cs)
This offers a slight speedup and slightly smaller memory usage compared to leaving the logging system...
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 DisableCategory(LogFlags category)
size_t m_max_buffer_memusage GUARDED_BY(m_cs)
void EnableCategory(LogFlags category)
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
uint32_t GetCategoryMask() 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.
CSipHasher & Write(uint64_t data)
Hash a 64-bit integer worth of data.
Path class wrapper to block calls to the fs::path(std::string) implicit constructor and the fs::path:...
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.
static void LogPrintf_(std::source_location &&source_loc, BCLog::LogFlags flag, BCLog::Level level, bool should_ratelimit, const char *fmt, const Args &...args)
BCLog::Logger & LogInstance()
static const bool DEFAULT_LOGSOURCELOCATIONS
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
Implement std::hash so RCUPtr can be used as a key for maps or sets.
constexpr auto MakeUCharSpan(V &&v) -> decltype(UCharSpanCast(Span{std::forward< V >(v)}))
Like the Span constructor, but for (const) uint8_t member types only.
auto Join(const std::vector< T > &list, const BaseType &separator, UnaryOp unary_op) -> decltype(unary_op(list.at(0)))
Join a list of items.
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(...)