Skip to content

kernel: use struct-based logging and simplify logging interface - #34374

Merged
sedited merged 6 commits into
bitcoin:masterfrom
stickies-v:2026-01/kernel-logging-layering-predicate
Oct 8, 2026
Merged

sedited merged 6 commits into
bitcoin:masterfrom
stickies-v:2026-01/kernel-logging-layering-predicate

Conversation

@stickies-v

@stickies-v stickies-v commented Jan 21, 2026 •

Copy link
Copy Markdown
Contributor

tl;dr: kernel logging is cumbersome. This PR delivers log entries as a struct instead of a formatted string, and simplifies the kernel logging interface. Closes #34062.

Motivation

The bitcoinkernel library (#27587) exposes functionality to interface with the kernel logging. This includes registering callbacks for log statements, level/category filtering, string formatting options, and more.

Kernel logging has a few problems:

  • callbacks operate on formatted strings, so users need to parse the string to get the timestamp, category, level, ... based on which options are set. This is cumbersome, brittle, and inefficient.
  • the filtering interface is not really intuitive, requiring users to call combinations of btck_logging_set_level_category and btck_logging_enable_category when they want to produce debug or trace logs. The level/category system makes sense for node, because it directly controls what gets written to disk and stdout, and there are quite a lot more categories producing logs. Kernel doesn't really need this - users control what happens to the logs, and can do any filtering/manipulation in the callback they provide.
  • the node logging infrastructure has quite a bit more functionality than is necessary for a library, including ratelimiting, log formatting, outputting, buffering, ... This introduces unnecessary code and interface complexity.

Approach

Log generation (util/log.h: macros, util::log::Entry, and the ShouldDebugLog/ShouldTraceLog/Log hooks an application must provide) was already separated from log handling (logging.h) in #34465 and subsequent PRs. This PR gives bitcoinkernel its own implementation of those hooks, so it no longer depends on logging.cpp, and upgrades the C API to deliver struct-based entries. Node logging is not changed.

  1. Preparatory work: expose the missing levels and categories (WARNING, ERROR, TXPACKAGES, LOCK) and the btck_LogEntry struct, add Name() helpers to the C++ wrapper, and remove btck_logging_set_options and btck_logging_disable (with struct-based entries there is no kernel-side format to configure, and without buffering there is nothing to disable).
  2. Add KernelLogger: a kernel-owned backend that holds the registered callbacks and the minimum level, and converts each util::log::Entry into a btck_LogEntry. Introduced in a separate commit to keep the scope of the behaviour-changing commit smaller.
  3. Update the bitcoinkernel C API: btck_LogCallback receives a btck_LogEntry instead of a string, the util::log hooks are implemented on KernelLogger, logging.cpp is dropped from the kernel build, and the logging configuration interface is reduced to btck_logging_set_min_level().

Behaviour changes for consumers (also described in each commit message):

  • Logging callbacks deliver structs instead of formatted strings, and the entire logging interface is simplified.
  • Filtering is levels-based only and can also filter Info and above. Debug/Trace apply to all categories, consumers can filter on btck_LogEntry::category (but string formatting is done for the entire level, instead of per enabled category).
  • Entries logged before the first connection are dropped instead of buffered.
  • Messages are delivered unescaped and without a trailing newline.

Appendix

bitcoinkernel C logging interface

typedef struct {
    const char* message;    //! Log message text.
    size_t message_len;
    const char* thread_name;    //! Name of the thread that produced the log message.
    size_t thread_name_len; 
    int64_t timestamp_ns;    //! Wall-clock time when the entry was logged, in nanoseconds since the Unix epoch.
    int64_t mocktime_s;    //! Mock time in effect when the entry was logged, in seconds since the Unix epoch, or 0 if no mock time is set (see btck_set_mock_time).
    const char* file_name;    //! Name of the source file that produced the log statement.
    size_t file_name_len;
    const char* function_name;    //! Name of the function that produced the log message.
    size_t function_name_len;
    uint32_t line;    //! Line number of the source code that produced the log statement.
    btck_LogLevel level;    //! Log severity level.
    btck_LogCategory category;    //! Log category.
} btck_LogEntry;

typedef void (*btck_LogCallback)(void* user_data, const btck_LogEntry* entry);

BITCOINKERNEL_API void btck_logging_set_min_level(btck_LogLevel level);

BITCOINKERNEL_API btck_LoggingConnection* BITCOINKERNEL_WARN_UNUSED_RESULT btck_logging_connection_create(
    btck_LogCallback log_callback,
    void* user_data,
    btck_DestroyCallback user_data_destroy_callback) BITCOINKERNEL_ARG_NONNULL(1);

BITCOINKERNEL_API void btck_logging_connection_destroy(btck_LoggingConnection* logging_connection);

@DrahtBot

DrahtBot commented Jan 21, 2026 •

Copy link
Copy Markdown
Contributor

The following sections might be updated with supplementary metadata relevant to reviewers and maintainers.

External sites

Reviews

See the guideline and AI policy for information on the review process.

Type Reviewers
ACK w0xlt, musaHaruna, sedited
Concept ACK yuvicc
Stale ACK ryanofsky

If your review is incorrectly listed, please copy-paste <!--meta-tag:bot-skip--> into the comment that the bot should ignore.

Conflicts

Reviewers, this pull request conflicts with the following ones:

  • #36353 (kernel: don't reuse cached CheckBlock results across params by FlashWayne)
  • #36326 (kernel: Use typed errors for fatal and flush error notifications by arejula27)
  • #36000 (validation: prefetch blocks while connecting by l0rinc)
  • #35641 (kernel: Add script evaluation tracer by sedited)
  • #35322 (logging: streamline Logger state and drop redundant methods by ryanofsky)
  • #35187 (kernel: Block validation without a complete UTXO set by sedited)
  • #33847 (kernel: Attach logging connections to contexts, per-connection log levels by ryanofsky)
  • #28690 (build: Introduce internal kernel library by sedited)

If you consider this pull request important, please also help to review the conflicting pull requests. Ideally, start with the one that should be merged first.

@stickies-v
stickies-v force-pushed the 2026-01/kernel-logging-layering-predicate branch from e1a58bc to 446f523 Compare January 21, 2026 20:15
@DrahtBot

Copy link
Copy Markdown
Contributor

🚧 At least one of the CI tasks failed.
Task tidy: https://github.com/bitcoin/bitcoin/actions/runs/21223722631/job/61065673932
LLM reason (✨ experimental): Linker errors due to unresolved detail::InitLogger() from logging.cpp.o, causing the build/test script to fail.

Hints

Try to run the tests locally, according to the documentation. However, a CI failure may still
happen due to a number of reasons, for example:

  • Possibly due to a silent merge conflict (the changes in this pull request being
    incompatible with the current code in the target branch). If so, make sure to rebase on the latest
    commit of the target branch.

  • A sanitizer issue, which can only be found by compiling with the sanitizer and running the
    affected test.

  • An intermittent issue.

Leave a comment here, if you need help tracking down a confusing failure.

@stickies-v
stickies-v force-pushed the 2026-01/kernel-logging-layering-predicate branch from 446f523 to c20ff4c Compare January 21, 2026 20:26
@github-project-automation github-project-automation Bot moved this to Architecture & Performance in The libbitcoinkernel Project Jan 22, 2026
@sedited sedited moved this from Architecture & Performance to API Development in The libbitcoinkernel Project Jan 22, 2026
@stickies-v
stickies-v force-pushed the 2026-01/kernel-logging-layering-predicate branch from c20ff4c to 0d075e3 Compare January 22, 2026 17:52
Comment thread src/logging.h Resolved
Comment thread src/util/log.h Resolved

@musaHaruna musaHaruna left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Tested 5c213d0 on macOS arm64 with a Debug build. My review was limited to the connection/disconnection message fields and cleanup when connection creation fails.

I started from the existing logging test and checked the fields attached to the connection/disconnection messages. The existing test counts these messages; I also checked their level and category i.e:

BOOST_CHECK_EQUAL(entry.message, "Logger connected.");
BOOST_CHECK(entry.level == LogLevel::DEBUG_LEVEL);
BOOST_CHECK(entry.category == LogCategory::KERNEL);

I checked the same fields for "Logger disconnecting.". All checks passed.

I also checked what happens when creating a connection fails by making a memory request fail on purpose. I found one case where the supplied data was not cleaned up, and another where the docs promise a cleanup callback that does not run when the data is null. Details inline below.

Comment thread src/kernel/bitcoinkernel.cpp Resolved
Comment thread src/kernel/bitcoinkernel.h Resolved
@stickies-v

Copy link
Copy Markdown
Contributor Author

Force-pushed to address review comments from @musaHaruna:

  • construct UserData before calling GetKernelLogger() to ensure user_data is always freed on error
  • update user_data_destroy_callback docstring to highlight that the destroy cb is not called when user_data is null

@ryanofsky ryanofsky left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Code review ACK ad66992. Since my last review: added an atomic callback count so nothing is locked or formatted when no connection is registered, MockTime() returns an optional time point, the LOCK category no longer asserts in intermediate commits, and user_data is now freed if getting the kernel logger throws.

Thanks for considering the other suggestions, the reasons for leaving them out make sense to me.

Comment thread src/kernel/bitcoinkernel.cpp Resolved
Comment thread src/kernel/bitcoinkernel.h Resolved
Comment thread src/kernel/bitcoinkernel.h Resolved
Comment thread src/kernel/bitcoinkernel.h Resolved
Comment thread src/logging.h Resolved
Comment thread src/kernel/bitcoinkernel.h Resolved
Comment thread src/kernel/bitcoinkernel.cpp Resolved
Introduce the btck_LogEntry struct the logging callback will use in
a future commit (instead of the current string argument). The struct
is not yet used.

The level and category definitions move up so the callback typedef can
reference btck_LogEntry; review with --color-moved.

No behaviour change. Part of a series of commits to make kernel logging
struct-based instead of string-based.
Convenience functions for consumers that want to format levels and
categories.

No behaviour change. Part of a series of commits to make kernel logging
struct-based instead of string-based.
Both functions lose their purpose once the kernel logger is no longer
coupled to the node logger: formatting becomes the consumer's job, and
nothing is buffered before a connection exists, so there is nothing to
disable. Remove them early to simplify the next commits.

Behaviour change until the backend switch later in this series:
- strings are delivered in BCLog::Logger's default format
- the 1MB pre-connection buffer cannot be turned off.

Part of a series of commits to make kernel logging struct-based instead
of string-based.
Add the kernel's own logging backend, unused until the next commit
switches the C API over to it.

Callbacks run while the logger's mutex is held: invocations are
serialized, and unregistering waits for an in-flight callback.

Callbacks are typed with a local LogCallback alias carrying the
struct-based signature, because btck_LogCallback still delivers a
string at this point. The next commit changes the typedef and replaces
the alias.

No behaviour change. Part of a series of commits to make kernel logging
struct-based instead of string-based.
Update btck_LogCallback to use struct-based logging and drop logging.cpp
from the kernel build.

Since consumers can now easily filter by category, simplify the logging
configuration to just btck_logging_set_min_level.

Behaviour changes for consumers:
- Filtering is now purely levels-based, and consumers can choose any
  level they like. Debug and Trace logging applies to all categories,
  further filtering should be done client-side.
  Note: evaluation remains unchanged: Debug and Trace statements are
  only evaluated when they are requested, Info and above is always
  evaluated.
- Entries logged before the first connection are dropped, not buffered.
- Trailing newlines are stripped, callback exceptions are swallowed,
  and connection create and destroy no longer take cs_main.
- Log messages are no longer escaped, this can be done client-side.
- btck_LogCategory_ALL is replaced by btck_LogCategory_NONE, since
  uncategorized entries do not belong to all categories.

KernelLogger moves into the anonymous namespace now that every member
is used. It stayed outside in the previous commit to avoid unused
member warnings.

Node logging is unchanged. Final commit of the series to make kernel
logging struct-based instead of string-based.

@stickies-v stickies-v left a comment

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Force-pushed to address review comments from @ryanofsky and @w0xlt:

  • replace btck_LogCategory_ALL and btck_LogCategory_UNKNOWN with a single btck_LogCategory_NONE
  • document that btck_LogEntry::message is not escaped
  • docstring fixes for btck_LogCallback and btck_logging_connection_create
  • remove the now-unused BCLog::Logger::NumConnections()

Comment thread src/kernel/bitcoinkernel.cpp Resolved
Comment thread src/kernel/bitcoinkernel.cpp Resolved
Comment thread src/kernel/bitcoinkernel.h Resolved
Comment thread src/kernel/bitcoinkernel.h Resolved
Comment thread src/kernel/bitcoinkernel.h Resolved
Comment thread src/kernel/bitcoinkernel.h Resolved
Comment thread src/logging.h Resolved

@w0xlt w0xlt left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

ACK eb08654

@musaHaruna musaHaruna left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Code Review ACK eb08654

Thanks for incorporating my suggestions @stickies-v.

@yuvicc

yuvicc commented Oct 7, 2026 •

Copy link
Copy Markdown
Contributor

Concept ACK

I've had issues parsing logs when using the kernel API, the changes here looks structured and useful improvement for kernel API users.

@sedited sedited left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Nice, ACK eb08654

There are some things that could still be worked out, like enabling debug logging only when the category is set, and settling the global vs. instantiated logging question, but we can have those in the coming weeks.

Comment on lines +393 to +423
typedef struct {
//! Log message text. Not escaped, so it may contain newlines and other
//! control characters.
const char* message;
//! Length of message.
size_t message_len;
//! Name of the thread that produced the log message.
const char* thread_name;
//! Length of thread_name.
size_t thread_name_len;
//! Wall-clock time when the entry was logged, in nanoseconds since the
//! Unix epoch.
int64_t timestamp_ns;
//! Mock time in effect when the entry was logged, in seconds since the Unix
//! epoch, or 0 if no mock time is set (see btck_set_mock_time).
int64_t mocktime_s;
//! Name of the source file that produced the log statement.
const char* file_name;
//! Length of file_name.
size_t file_name_len;
//! Name of the function that produced the log message.
const char* function_name;
//! Length of function_name.
size_t function_name_len;
//! Line number of the source code that produced the log statement.
uint32_t line;
//! Log severity level.
btck_LogLevel level;
//! Log category.
btck_LogCategory category;
} btck_LogEntry;

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Might this be better as an opaque struct? I'm not convinced actually, since these are mostly cheap views into the data, and it shouldn't matter much if they need to be copied from this struct or through getter functions.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I suppose an opaque struct would be better for ABI stability and consistency of the interface, and I think it might be a bit more straightforward for FFI. Performance seems to be a bit worse (few nanoseconds per callback), but compared to the cost of string formatting etc is not super meaningful. Specifically, there's more indirection for every field that's accessed, but fields that aren't accessed aren't constructed for nothing.

I don't have a strong view either way. I initially felt like an opaque struct would require an unreasonably large API surface for the functionality, but it does seem like the mildly better approach. The increased API surface is trivial in nature so I don't think it's that bad either.

Unless people feel strongly about this, would prefer leaving as-is and address in a quick follow-up if there's appetite for it? This PR has had a lot of activity and revisions already.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Done in #36584

@yuvicc

yuvicc commented Oct 9, 2026

Copy link
Copy Markdown
Contributor

post-merge ACK eb08654

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

Status: Done or Closed or Rethinking

Development

Successfully merging this pull request may close these issues.

RFC: separate kernel logging infrastructure

9 participants