Inside Bitcoin
Opening the selected file…
Inside Bitcoin
Opening the selected file…
The code behind the network, with room to understand it.
Release published 2026-10-28 · Snapshot fetched 2026-11-01. Latest stable release at fetch time; development branches and Git history are excluded. Only the selected code window and visible folders load here.
1// Copyright (c) The Bitcoin Core developers2// Distributed under the MIT software license, see the accompanying3// file COPYING or http://www.opensource.org/licenses/mit-license.php.5#ifndef BITCOIN_UTIL_LOG_H6#define BITCOIN_UTIL_LOG_H8// This header works in tandem with `logging/categories.h`9// to expose the complete logging interface.10#include <logging/categories.h> // IWYU pragma: export11#include <tinyformat.h>12#include <util/check.h>13#include <util/threadnames.h>14#include <util/time.h>16#include <cstdint>17#include <source_location>18#include <string>19#include <string_view>21/// Like std::source_location, but allowing to override the function name.22class SourceLocation23{24public:25/// The func argument must be constructed from the C++11 __func__ macro.26/// Ref: https://en.cppreference.com/w/cpp/language/function.html#func27/// Non-static string literals are not supported.28explicit SourceLocation(29const char* func,30std::source_location loc = std::source_location::current())31: m_func{func}, m_loc{loc} {}33std::string_view file_name() const { return m_loc.file_name(); }34std::uint_least32_t line() const { return m_loc.line(); }35std::string_view function_name_short() const { return m_func; }37private:38std::string_view m_func;39std::source_location m_loc;40};42namespace util::log {43/** Opaque to util::log; interpreted by consumers (e.g., BCLog::LogFlags). */44using Category = uint64_t;46//! Structure and constant for tagging not to rate limit.47struct NoRateLimitTag {48explicit NoRateLimitTag() = default;49};50inline constexpr NoRateLimitTag NO_RATE_LIMIT{};52enum class Level {53Trace = 0, // High-volume or detailed logging for development/debugging54Debug, // Reasonably noisy logging, but still usable in production55Info, // Default56Warning,57Error,58};60struct Entry {61Category category;62Level level;63bool should_ratelimit{false}; //!< Hint for consumers if this entry should be ratelimited64SystemClock::time_point timestamp{SystemClock::now()};65std::chrono::seconds mocktime{GetMockTime()};66std::string thread_name{util::ThreadGetInternalName()};67SourceLocation source_loc;68std::string message;69};71/// Return whether messages with specified category should be debug logged.72/// Applications using the logging library need to provide this.73bool ShouldDebugLog(Category category);75/// Return whether messages with specified category should be trace logged.76/// Applications using the logging library need to provide this.77bool ShouldTraceLog(Category category);79/** Send message to be logged. Applications using the logging library need to provide this. */80void Log(Entry entry);82template <typename... Args>83inline void LogPrintFormatInternal_(SourceLocation&& source_loc, BCLog::LogFlags flag, util::log::Level level, bool should_ratelimit, util::ConstevalFormatString<sizeof...(Args)> fmt, const Args&... args)84{85std::string log_msg;86try {87log_msg = tfm::format(fmt, args...);88} catch (tinyformat::format_error& fmterr) {89log_msg = "Error \"" + std::string{fmterr.what()} + "\" while formatting log message: " + fmt.fmt;90}91util::log::Log(util::log::Entry{92.category = flag,93.level = level,94.should_ratelimit = should_ratelimit,95.source_loc = std::move(source_loc),96.message = std::move(log_msg)});97}99template <typename... Args>100inline void LogPrintFormatInternal(SourceLocation&& source_loc, BCLog::LogFlags flag, util::log::Level level, util::ConstevalFormatString<sizeof...(Args)> fmt, const Args&... args)101{102return LogPrintFormatInternal_(std::move(source_loc), flag, level, /*should_ratelimit=*/true, fmt, args...);103}105template <typename... Args>106inline void LogPrintFormatInternal(SourceLocation&& source_loc, BCLog::LogFlags flag, util::log::Level level, util::log::NoRateLimitTag, util::ConstevalFormatString<sizeof...(Args)> fmt, const Args&... args)107{108return LogPrintFormatInternal_(std::move(source_loc), flag, level, /*should_ratelimit=*/false, fmt, args...);109}110} // namespace util::log112namespace BCLog {113//! Alias for compatibility. Prefer util::log::Level over BCLog::Level in new code.114using Level = util::log::Level;115} // namespace BCLog117// Allow __func__ to be used in any context without warnings:118// NOLINTNEXTLINE(bugprone-lambda-function-name)119#define detail_LogWithSrcLoc(category, level, ...) util::log::LogPrintFormatInternal(SourceLocation{__func__}, category, level, __VA_ARGS__)121// Log unconditionally. Uses basic rate limiting to mitigate disk filling attacks.122// Be conservative when using functions that unconditionally log to debug.log!123// It should not be the case that an inbound peer can fill up a user's storage124// with debug.log entries.125#define LogInfo(...) detail_LogWithSrcLoc(BCLog::LogFlags::ALL, util::log::Level::Info, __VA_ARGS__)126#define LogWarning(...) detail_LogWithSrcLoc(BCLog::LogFlags::ALL, util::log::Level::Warning, __VA_ARGS__)127#define LogError(...) detail_LogWithSrcLoc(BCLog::LogFlags::ALL, util::log::Level::Error, __VA_ARGS__)129// Use a macro instead of a function for conditional logging to prevent130// evaluating arguments when logging for the category is not enabled.132// Log by prefixing the output with the passed category name and severity level. This logs conditionally if133// the category is allowed. No rate limiting is applied, because users specifying -debug are assumed to be134// developers or power users who are aware that -debug may cause excessive disk usage due to logging.135#define detail_LogIfCategoryAndLevelEnabled(category, shouldlog, level, ...) \136do { \137if (shouldlog(category)) { \138detail_LogWithSrcLoc((category), (level), util::log::NO_RATE_LIMIT, __VA_ARGS__); \139} \140} while (0)142// Log conditionally, prefixing the output with the passed category name.143#define LogDebug(category, ...) detail_LogIfCategoryAndLevelEnabled(category, util::log::ShouldDebugLog, util::log::Level::Debug, __VA_ARGS__)144#define LogTrace(category, ...) detail_LogIfCategoryAndLevelEnabled(category, util::log::ShouldTraceLog, util::log::Level::Trace, __VA_ARGS__)146#endif // BITCOIN_UTIL_LOG_H
Independent explanations by MyBitcoinExplorer. Not affiliated with or endorsed by Bitcoin Core. Guides are educational and do not replace the source or its tests.
Bitcoin Core source © its contributors, distributed under the MIT license. Original notices and bundled third-party licenses are retained in the source tree.