49 return fwrite(str.data(), 1, str.size(), fp);
57 assert(m_fileout ==
nullptr);
66 setbuf(m_fileout,
nullptr);
75 if (m_buffer_lines_discarded > 0) {
78 while (!m_msgs_before_open.empty()) {
79 const auto& buflog = m_msgs_before_open.front();
80 std::string
s{buflog.str};
81 FormatLogStrInPlace(
s, buflog.category, buflog.level, buflog.source_file, buflog.source_line, buflog.logging_function, buflog.threadname, buflog.now, buflog.mocktime);
82 m_msgs_before_open.pop_front();
86 for (
const auto& cb : m_print_callbacks) {
90 m_cur_buffer_memusage = 0;
100 if (m_fileout !=
nullptr) fclose(m_fileout);
102 m_print_callbacks.clear();
104 m_cur_buffer_memusage = 0;
105 m_buffer_lines_discarded = 0;
106 m_msgs_before_open.clear();
114 assert(m_print_callbacks.empty());
116 m_print_to_file =
false;
117 m_print_to_console =
false;
123 m_categories |= flag;
130 EnableCategory(flag);
136 m_categories &= ~flag;
143 DisableCategory(flag);
149 return (m_categories.load(std::memory_order_relaxed) & category) != 0;
158 if (!WillLogCategory(category))
return false;
161 const auto it{m_category_log_levels.find(category)};
162 return level >= (it == m_category_log_levels.end() ? LogLevel() : it->second);
195#ifdef DEBUG_LOCKCONTENTION
207 std::unordered_map<BCLog::LogFlags, std::string>
out;
208 for (
const auto& [
k, v] : in) {
209 const bool inserted{
out.emplace(v,
k).second};
218 if (str.empty() || str ==
"1" || str ==
"all") {
257static std::optional<BCLog::Level>
GetLogLevel(std::string_view level_str)
259 if (level_str ==
"trace") {
261 }
else if (level_str ==
"debug") {
263 }
else if (level_str ==
"info") {
265 }
else if (level_str ==
"warning") {
267 }
else if (level_str ==
"error") {
276 std::vector<LogCategory>
ret;
293 return Join(std::vector<BCLog::Level>{levels.begin(), levels.end()},
", ", [](
BCLog::Level level) {
return LogLevelToStr(level); });
298 std::string strStamped;
300 if (!m_log_timestamps)
303 const auto now_seconds{std::chrono::time_point_cast<std::chrono::seconds>(now)};
305 if (m_log_time_micros && !strStamped.empty()) {
306 strStamped.pop_back();
307 strStamped +=
strprintf(
".%06dZ", Ticks<std::chrono::microseconds>(now - now_seconds));
327 for (
char ch_in : str) {
328 uint8_t ch = (uint8_t)ch_in;
329 if ((ch >= 32 || ch ==
'\n') && ch !=
'\x7f') {
343 const bool has_category{m_always_print_category_level || category !=
LogFlags::ALL};
346 if (!has_category && level ==
Level::Info)
return {};
353 if (m_always_print_category_level || !has_category || level !=
Level::Debug) {
357 if (has_category)
s +=
":";
372 if (!str.ends_with(
'\n')) str.push_back(
'\n');
374 str.insert(0, GetLogPrefix(category, level));
376 if (m_log_sourcelocations) {
380 if (m_log_threadnames) {
381 str.insert(0,
strprintf(
"[%s] ", (threadname.empty() ?
"unknown" : threadname)));
384 str.insert(0, LogTimestampStr(now, mocktime));
390 return LogPrintStr_(str, logging_function, source_file, source_line, category, level);
400 .
now=SystemClock::now(),
403 .logging_function=std::string(logging_function),
404 .source_file=std::string(source_file),
406 .source_line=source_line,
410 m_cur_buffer_memusage +=
MemUsage(buf);
411 m_msgs_before_open.push_back(std::move(buf));
414 while (m_cur_buffer_memusage > m_max_buffer_memusage) {
415 if (m_msgs_before_open.empty()) {
416 m_cur_buffer_memusage = 0;
419 m_cur_buffer_memusage -=
MemUsage(m_msgs_before_open.front());
420 m_msgs_before_open.pop_front();
421 ++m_buffer_lines_discarded;
429 if (m_print_to_console) {
431 fwrite(str_prefixed.data(), 1, str_prefixed.size(), stdout);
434 for (
const auto& cb : m_print_callbacks) {
437 if (m_print_to_file) {
438 assert(m_fileout !=
nullptr);
442 m_reopen_file =
false;
445 setbuf(new_fileout,
nullptr);
447 m_fileout = new_fileout;
457 constexpr size_t RECENT_DEBUG_HISTORY_SIZE = 10 * 1000000;
459 assert(!m_file_path.empty());
467 log_size = fs::file_size(m_file_path);
468 }
catch (
const fs::filesystem_error&) {}
472 if (file && log_size > 11 * (RECENT_DEBUG_HISTORY_SIZE / 10))
475 std::vector<char> vch(RECENT_DEBUG_HISTORY_SIZE, 0);
476 if (fseek(file, -((
long)vch.size()), SEEK_END)) {
477 LogPrintf(
"Failed to shrink debug log file: fseek(...) failed\n");
481 int nBytes = fread(vch.data(), 1, vch.size(), file);
487 fwrite(vch.data(), 1, nBytes, file);
491 else if (file !=
nullptr)
499 m_log_level = level.value();
512 m_category_log_levels[flag] = level.value();
static std::string LogLevelToStr(BCLog::Level level)
Returns the string representation of a log level.
bool WillLogCategory(LogFlags category) const
std::string LogTimestampStr(SystemClock::time_point now, std::chrono::seconds mocktime) const
bool DefaultShrinkDebugFile() const
void SetCategoryLogLevel(const std::unordered_map< LogFlags, Level > &levels) EXCLUSIVE_LOCKS_REQUIRED(!m_cs)
void SetLogLevel(Level 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)
void FormatLogStrInPlace(std::string &str, LogFlags category, Level level, std::string_view source_file, int source_line, std::string_view logging_function, std::string_view threadname, SystemClock::time_point now, std::chrono::seconds mocktime) const
std::string GetLogPrefix(LogFlags category, Level level) const
void LogPrintStr(std::string_view str, std::string_view logging_function, std::string_view source_file, int source_line, BCLog::LogFlags category, BCLog::Level level) EXCLUSIVE_LOCKS_REQUIRED(!m_cs)
Send a string to the log output.
void DisconnectTestLogger() EXCLUSIVE_LOCKS_REQUIRED(!m_cs)
Only for testing.
std::string LogLevelsString() const
Returns a string with all user-selectable log levels.
void DisableCategory(LogFlags flag)
void LogPrintStr_(std::string_view str, std::string_view logging_function, std::string_view source_file, int source_line, BCLog::LogFlags category, BCLog::Level level) EXCLUSIVE_LOCKS_REQUIRED(m_cs)
Send a string to the log output (internal)
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...
constexpr size_t DEFAULT_MAX_LOG_BUFFER
FILE * fopen(const fs::path &p, const char *mode)
bool StartLogging(const ArgsManager &args)
static size_t MallocUsage(size_t alloc)
Compute the total memory used by allocating alloc bytes.
std::string ThreadGetInternalName()
Get the thread's internal (in-memory) name; used e.g.
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.
SystemClock::time_point now
std::string logging_function
std::chrono::seconds GetMockTime()
For testing.
std::string FormatISO8601DateTime(int64_t nTime)
ISO 8601 formatting is preferred.
constexpr int64_t count_seconds(std::chrono::seconds t)