logging: Move message formatting to util/log.h

With this change, callers can use util/log.h to emit log messages and do not need to
include the full logging implementation in logging.h.

There's a potential performance impact with this change from an extra
`strprintf` call in log statements where `Logger::WillLogCategoryLevel` returns
true but `Logger::Enabled` returns false. This happens when bitcoind is run
with `-noprinttoconsole -nodebuglogfile` options.

For background, log macro arguments are supposed to be evaluated when
`Logger::WillLogCategoryLevel` returns true, even if log output is not enabled.
Changing this behavior would be reasonable but needs consideration in a
separate PR since not evaluating arguments in log statements has the potential
to change non-logging behavior.

The extra `strprintf` call could have been avoided by expanding this change and
making the `ShouldLog()` function return a tri-state DO_LOG / DO_NOT_LOG /
DO_NOT_LOG_ONLY_EVALUATE_ARGS value instead of a bool, but this complexity did
not seem warranted.

Review with --color-moved=dimmed-zebra --color-moved-ws=ignore-all-space

Co-authored-by: Ryan Ofsky <ryan@ofsky.org>
This commit is contained in:
stickies-v
2025-12-16 15:37:21 +00:00
parent 001f0a428e
commit bb8e9e7c4c
3 changed files with 54 additions and 20 deletions

View File

@@ -602,3 +602,16 @@ bool BCLog::Logger::SetCategoryLogLevel(std::string_view category_str, std::stri
m_category_log_levels[flag] = level.value();
return true;
}
bool util::log::ShouldLog(Category category, Level level)
{
return LogInstance().WillLogCategoryLevel(static_cast<BCLog::LogFlags>(category), level);
}
void util::log::Log(util::log::Entry entry)
{
BCLog::Logger& logger{LogInstance()};
if (logger.Enabled()) {
logger.LogPrintStr(std::move(entry.message), std::move(entry.source_loc), static_cast<BCLog::LogFlags>(entry.category), entry.level, entry.should_ratelimit);
}
}