51 return fwrite(str.data(), 1, str.size(), fp);
59 assert(m_fileout ==
nullptr);
68 setbuf(m_fileout,
nullptr);
77 if (m_buffer_lines_discarded > 0) {
80 while (!m_msgs_before_open.empty()) {
81 const auto& buflog = m_msgs_before_open.front();
82 std::string s{buflog.str};
83 FormatLogStrInPlace(s, buflog.category, buflog.level, buflog.source_loc, buflog.threadname, buflog.now, buflog.mocktime);
84 m_msgs_before_open.pop_front();
88 for (
const auto& cb : m_print_callbacks) {
92 m_cur_buffer_memusage = 0;
102 if (m_fileout !=
nullptr) fclose(m_fileout);
104 m_print_callbacks.clear();
106 m_cur_buffer_memusage = 0;
107 m_buffer_lines_discarded = 0;
108 m_msgs_before_open.clear();
116 assert(m_print_callbacks.empty());
151 return (
m_categories.load(std::memory_order_relaxed) & category) != 0;
158 if (level >= BCLog::Level::Info)
return true;
163 const auto it{m_category_log_levels.find(category)};
164 return level >= (it == m_category_log_levels.end() ?
LogLevel() : it->second);
197#ifdef DEBUG_LOCKCONTENTION
198 {
"lock", BCLog::LOCK},
211 std::unordered_map<BCLog::LogFlags, std::string> out;
212 for (
const auto& [
k, v] : in) {
213 const bool inserted{out.emplace(v,
k).second};
222 if (str.empty() || str ==
"1" || str ==
"all") {
237 case BCLog::Level::Trace:
239 case BCLog::Level::Debug:
241 case BCLog::Level::Info:
243 case BCLog::Level::Warning:
245 case BCLog::Level::Error:
261static std::optional<BCLog::Level>
GetLogLevel(std::string_view level_str)
263 if (level_str ==
"trace") {
264 return BCLog::Level::Trace;
265 }
else if (level_str ==
"debug") {
266 return BCLog::Level::Debug;
267 }
else if (level_str ==
"info") {
268 return BCLog::Level::Info;
269 }
else if (level_str ==
"warning") {
270 return BCLog::Level::Warning;
271 }
else if (level_str ==
"error") {
272 return BCLog::Level::Error;
280 std::vector<LogCategory>
ret;
291 return {BCLog::Level::Info, BCLog::Level::Debug, BCLog::Level::Trace};
302 std::string strStamped;
307 const auto now_seconds{std::chrono::time_point_cast<std::chrono::seconds>(now)};
310 strStamped.pop_back();
331 for (
char ch_in : str) {
332 uint8_t ch = (uint8_t)ch_in;
333 if ((ch >= 32 || ch ==
'\n') && ch !=
'\x7f') {
350 if (!has_category && level == Level::Info)
return {};
361 if (has_category) s +=
":";
380 SchedulerFunction&& scheduler_func, uint64_t max_bytes, std::chrono::seconds reset_window)
382 auto limiter{std::shared_ptr<LogRateLimiter>(
new LogRateLimiter(max_bytes, reset_window))};
383 std::weak_ptr<LogRateLimiter> weak_limiter{limiter};
384 auto reset = [weak_limiter] {
385 if (
auto shared_limiter{weak_limiter.lock()}) shared_limiter->Reset();
387 scheduler_func(reset, limiter->m_reset_window);
393 const std::string& str)
396 auto& stats{m_source_locations.try_emplace(source_loc,
m_max_bytes).first->second};
409 if (!str.ends_with(
'\n')) str.push_back(
'\n');
418 str.insert(0,
strprintf(
"[%s] ", (threadname.empty() ?
"unknown" : threadname)));
427 return LogPrintStr_(str, std::move(source_loc), category, level, should_ratelimit);
438 .now = SystemClock::now(),
442 .source_loc = std::move(source_loc),
443 .category = category,
446 m_cur_buffer_memusage +=
MemUsage(buf);
447 m_msgs_before_open.push_back(std::move(buf));
450 while (m_cur_buffer_memusage > m_max_buffer_memusage) {
451 if (m_msgs_before_open.empty()) {
452 m_cur_buffer_memusage = 0;
455 m_cur_buffer_memusage -=
MemUsage(m_msgs_before_open.front());
456 m_msgs_before_open.pop_front();
457 ++m_buffer_lines_discarded;
464 bool ratelimit{
false};
465 if (should_ratelimit && m_limiter) {
466 auto status{m_limiter->Consume(source_loc, str_prefixed)};
470 "Excessive logging detected from %s:%d (%s): >%d bytes logged during "
471 "the last time window of %is. Suppressing logging to disk from this "
472 "source location until time window resets. Console logging "
473 "unaffected. Last log entry.",
474 source_loc.file_name(), source_loc.line(), source_loc.function_name_short(),
475 m_limiter->m_max_bytes,
485 if (m_limiter && m_limiter->SuppressionsActive()) {
486 str_prefixed.insert(0,
"[*] ");
491 fwrite(str_prefixed.data(), 1, str_prefixed.size(), stdout);
494 for (
const auto& cb : m_print_callbacks) {
498 assert(m_fileout !=
nullptr);
505 setbuf(new_fileout,
nullptr);
507 m_fileout = new_fileout;
517 constexpr size_t RECENT_DEBUG_HISTORY_SIZE = 10 * 1000000;
528 }
catch (
const fs::filesystem_error&) {}
532 if (file && log_size > 11 * (RECENT_DEBUG_HISTORY_SIZE / 10))
535 std::vector<char> vch(RECENT_DEBUG_HISTORY_SIZE, 0);
536 if (fseek(file, -((
long)vch.size()), SEEK_END)) {
537 LogWarning(
"Failed to shrink debug log file: fseek(...) failed");
541 int nBytes = fread(vch.data(), 1, vch.size(), file);
547 fwrite(vch.data(), 1, nBytes, file);
551 else if (file !=
nullptr)
557 decltype(m_source_locations) source_locations;
560 source_locations.swap(m_source_locations);
563 for (
const auto& [source_loc, stats] : source_locations) {
564 if (stats.m_dropped_bytes == 0)
continue;
567 "Restarting logging from %s:%d (%s): %d bytes were dropped during the last %ss.",
568 source_loc.file_name(), source_loc.line(), source_loc.function_name_short(),
602 m_category_log_levels[flag] = level.value();
auto Join(const C &container, const S &separator, UnaryOp unary_op)
Join all container items.
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)
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
bool WillLogCategory(LogFlags category) const
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
bool DefaultShrinkDebugFile() const
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
bool WillLogCategoryLevel(LogFlags category, Level level) const 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)
std::string GetLogPrefix(LogFlags category, Level level) const
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 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.
bool Enabled() const EXCLUSIVE_LOCKS_REQUIRED(!m_cs)
Returns whether logs will be written to any output.
void DisableCategory(LogFlags flag)
Like std::source_location, but allowing to override the function name.
std::string_view function_name_short() const
std::string_view file_name() const
std::uint_least32_t line() const
#define LogPrintLevel_(category, level, should_ratelimit,...)
static constexpr std::array< BCLog::Level, 3 > LogLevelsList()
Log severity levels that can be selected by the user.
static int FileWriteStr(std::string_view str, FILE *fp)
static std::string LogCategoryToStr(BCLog::LogFlags category)
bool GetLogCategory(BCLog::LogFlags &flag, std::string_view str)
Return true if str parses as a log category and set the flag.
static size_t MemUsage(const BCLog::Logger::BufferedLog &buflog)
static const std::map< std::string, BCLog::LogFlags, std::less<> > LOG_CATEGORIES_BY_STR
BCLog::Logger & LogInstance()
static const std::unordered_map< BCLog::LogFlags, std::string > LOG_CATEGORIES_BY_FLAG
const char *const DEFAULT_DEBUGLOGFILE
static std::optional< BCLog::Level > GetLogLevel(std::string_view level_str)
constexpr auto MAX_USER_SETABLE_SEVERITY_LEVEL
static const bool DEFAULT_LOGIPS
std::string LogEscapeMessage(std::string_view str)
Belts and suspenders: make sure outgoing log messages don't contain potentially suspicious characters...
util::log::Level Level
Alias for compatibility. Prefer util::log::Level over BCLog::Level in new code.
constexpr size_t DEFAULT_MAX_LOG_BUFFER
FILE * fopen(const fs::path &p, const char *mode)
static size_t DynamicUsage(const int8_t &v)
Dynamic memory usage for built-in types is zero.
static size_t MallocUsage(size_t alloc)
Compute the total memory used by allocating alloc bytes.
void Log(Entry entry)
Send message to be logged.
uint64_t Category
Opaque to util::log; interpreted by consumers (e.g., BCLog::LogFlags).
bool ShouldLog(Category category, Level level)
Return whether messages with specified category and level should be logged.
std::string ThreadGetInternalName()
std::string_view RemovePrefixView(std::string_view str, std::string_view prefix)
auto Join(const C &container, const S &separator, UnaryOp unary_op)
Join all container items.
std::string_view RemovePrefixView(std::string_view str, std::string_view prefix)
uint64_t m_available_bytes
Remaining 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.
SourceLocation source_loc
bool should_ratelimit
Hint for consumers if this entry should be ratelimited.
std::chrono::seconds GetMockTime()
For testing.
std::string FormatISO8601DateTime(int64_t nTime)
ISO 8601 formatting is preferred.
constexpr auto TicksSinceEpoch(Timepoint t)
constexpr int64_t count_seconds(std::chrono::seconds t)
constexpr auto Ticks(Dur2 d)
Helper to count the seconds of a duration/time_point.