Skip to content

Conversation

@ryanofsky
Copy link
Contributor

@ryanofsky ryanofsky commented Jun 26, 2024

Pass Logger instances to BlockManager, CCoinsViewDB, CDBWrapper, Chainstate, ChainstateManager, CoinsViews, and CTxMemPool classes so libbitcoinkernel applications and tests have the option to control where log output goes instead of having all output sent to the global logger.

This PR is an alternative to #30338. It is more limited because it only changes kernel code while leaving other parts of the codebase alone. It also takes the opportunity to migrate legacy LogPrint / LogPrintf calls to the new log macros introduced in #28318.


This is based on #29256 + #33847. The non-base commits are:

@DrahtBot
Copy link
Contributor

DrahtBot commented Jun 26, 2024

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

Code Coverage & Benchmarks

For details see: https://corecheck.dev/bitcoin/bitcoin/pulls/30342.

Reviews

See the guideline for information on the review process.

Type Reviewers
Concept ACK sedited

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:

  • #33892 (policy: Remove individual transaction <minrelay restriction by instagibbs)
  • #33866 (refactor: Let CCoinsViewCache::BatchWrite return void by TheCharlatan)
  • #33856 (kernel, validation: Refactor ProcessNewBlock(Headers) to return BlockValidationState by yuvicc)
  • #33854 (validation: fix assumevalid is ignored during reindex by Eunovo)
  • #33796 (kernel: Expose CheckTransaction consensus validation function by w0xlt)
  • #33728 (test: Add bitcoin-chainstate test for assumeutxo functionality by stringintech)
  • #33680 (validation: do not wipe utxo cache for stats/scans/snapshots by l0rinc)
  • #33646 (log: check fclose() results and report safely in logging.cpp by cedwies)
  • #33629 (Cluster mempool by sdaftuar)
  • #33553 (validation: Improve warnings in case of chain corruption by mzumsande)
  • #33512 (coins: use number of dirty cache entries in flush warnings/logs by l0rinc)
  • #33324 (blocks: add -reobfuscate-blocks arg to xor existing blk/rev on startup by l0rinc)
  • #32950 (validation: remove BLOCK_FAILED_CHILD by stratospher)
  • #32545 (Replace cluster linearization algorithm with SFL by sipa)
  • #32427 ((RFC) kernel: Replace leveldb-based BlockTreeDB with flat-file based store by TheCharlatan)
  • #32317 (kernel: Separate UTXO set access from validation functions by TheCharlatan)
  • #32297 (bitcoin-cli: Add -ipcconnect option by ryanofsky)
  • #31860 (init: Take lock on blocks directory in BlockManager ctor by TheCharlatan)
  • #31723 (node: Add --debug_runs/-waitfordebugger + --debug_cmd by hodlinator)
  • #31644 (leveldb: show non-default options during init by l0rinc)
  • #31533 (fuzz: Add fuzz target for block index tree and related validation events by mzumsande)
  • #31382 (kernel: Flush in ChainstateManager destructor by TheCharlatan)
  • #31132 (validation: fetch block inputs on parallel threads >20% faster IBD by andrewtoth)
  • #30214 (refactor: Improve assumeutxo state representation by ryanofsky)
  • #29700 (kernel, refactor: return error status on all fatal errors by ryanofsky)
  • #29641 (scripted-diff: Use LogInfo over LogPrintf [WIP, NOMERGE, DRAFT] by maflcko)
  • #26022 (Add util::ResultPtr class by ryanofsky)
  • #25722 (refactor: Use util::Result class for wallet loading by ryanofsky)
  • #25665 (refactor: Add util::Result failure values, multiple error and warning messages by ryanofsky)
  • #19461 (multiprocess: Add bitcoin-gui -ipcconnect option by ryanofsky)
  • #19460 (multiprocess: Add bitcoin-wallet -ipcconnect option by ryanofsky)
  • #10102 (Multiprocess bitcoin by ryanofsky)

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.

LLM Linter (✨ experimental)

Possible typos and grammar issues:

  • instances is -> instance is [subject-verb agreement: "the logger instance is leaked" is grammatically correct]

2025-12-12

@sedited
Copy link
Contributor

sedited commented Jun 26, 2024

Concept ACK.

@DrahtBot
Copy link
Contributor

🚧 At least one of the CI tasks failed. Make sure to run all tests locally, according to the
documentation.

Possibly this is 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.

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

Debug: https://github.com/bitcoin/bitcoin/runs/26722091796

@ryanofsky
Copy link
Contributor Author

Updated 4542335 -> db1b9f7 (pr/gklog.1 -> pr/gklog.2, compare) moving code to an earlier commit to fix a "test-each-commit" test failure https://github.com/bitcoin/bitcoin/actions/runs/9684398780/job/26722073921?pr=30342, and cleaning up code to fix a clang-tidy warning https://cirrus-ci.com/task/5893151045451776

ryanofsky added a commit to ryanofsky/bitcoin that referenced this pull request Jul 3, 2024
Change LogInstance() function to no longer allocate (and leak) a BCLog::Logger
instance. Instead allow kernel applications to initialize their own logging
instances that can be returned by LogInstance().

This change is somewhat useful by itself, but more useful in combination with
bitcoin#30342. By itself, it gives kernel applications control over when the Logger is
created and destroyed and allows new instances to replace old ones. In
combination with bitcoin#30342 it allows multiple log instances to exist at the same
time, and different output to be sent to different instances.

This commit is built on top of bitcoin#30141 since it simplifies the implementation
somewhat.
ryanofsky and others added 12 commits December 12, 2025 05:49
Test will be extended in next commit to cover support for context objects.
Allow LogDebug(), LogTrace(), LogInfo(), LogWarning(), and LogError() macros to
accept context arguments to provide more information in log messages and more
control over logging to callers.

This functionality is used in followup PRs:

- bitcoin#30342 - To let libbitcoinkernel send
  output to specfic `BCLog::Logger` instances instead of a global instance, so
  output can be disambiguated and applications can have more control over
  logging.

- bitcoin#30343 - To replace custom
  `WalletLogPrintf` calls with standard logging calls that automatically include
  wallet names and don't log everything at info level.

This commit does not change behavior of current log prints or require them to
be updated. It includes tests and documentation covering the new functionality.

Co-Authored-By: Hodlinator <[email protected]>
Custom log contexts allow overridding log formatting and adding metadata such
as request ids or wallet names to log messages while still using standard
macros for logging. This is used to replace WalletLogPrintf() functions with
LogInfo() calls in followup PR bitcoin#30343.
Disallow passing BCLog category constants to LogInfo(), LogWarning(), and
LogError() macros, and disallow omitting BCLog categories when calling
LogDebug() and LogTrace() macros.

Additionally, drop category information from log output at higher levels as
suggested by Hodlinator
bitcoin#29256 (comment).

None of these restrictions are technically necessary, and not everybody
believes they are good. However, they have existed since the
Log{Trace,Debug,Info,Warning,Error} macros were introduced in bitcoin#28318, and
removing these restrictions is orthogonal to the goals of this PR which are:
(1) to allow the Log macros to work without accessing global state and (2) to
support local logging customization with additional metadata.

This change just more clearly documents the current logging restrictions and
provides better error messages to developers when enforcing them.

Co-Authored-By: Hodlinator <[email protected]>
Current kernel logging API is too complicated and too restrictive. This PR
tries to improves it.

I'd expect an API that supported logging to allow creating log streams with
different options and providing some way to specify which library operations
should be logged to which streams.

By contrast, the current API allows creating multiple log streams, but all the
streams receive the same messages because options can only be set globally and
the stream objects can't be passed to any kernel API functions. They are not
even referenced by the `btck_Context` struct which holds other shared state. If
no log streams are created, log messages are generated anyway, but they are
stored in a 1MB buffer and not sent anywhere, unless a log stream is created
later, at which point they are sent in bulk to that stream. More log streams
can be created after that, but they only receive new messages, not the buffered
ones. If log output is not needed, a btck_logging_disable() call is required to
prevent log messages from accumulating in the 1MB buffer. Calling this will
abort the program if any log streams were created before it was called, and
also abort the program if any new log streams are created later.

None of these behaviors seem necessary or ideal, and it would be better to
provide a simpler logging API that allows creating a log stream, setting
options on it, registering it with the `btck_Context` instance and receiving
log messages from it. Another advantage of this approach is that it could allow
(with bitcoin#30342) different log streams to be used for different purposes, which
would be not be possible with the current interface.
Pass Logger instances to BlockManager, CCoinsViewDB, CDBWrapper,
ChainstateManager, and CoinsViews instances so libbitcoinkernel applications
and test code have the option to control where log output goes instead of
having all output sent to the global logger.

This commit just passes the logger objects without using them. The next commit
updates log print statements to use the new objects.
This is a mechanical change updating kernel code that currently uses the global
log instance to log to local instances instead.
This allows libbitcoinkernel applications and test code to have the option to
control where log output goes instead of having all output sent to the global
logger.
Change LogInstance() function to no longer allocate (and leak) a BCLog::Logger
instance. Instead allow kernel applications to initialize their own logging
instances that can be returned by LogInstance().

The LogInstance() function is not actually used for the majority of logging in
kernel code. Most kernel log output goes directly to BCLog::Logger instances
specified when kernel objects like ChainstateManager and CTxMemPool are
constructed, which allows applications to create multiple Logger instances and
control which log output is sent to them.

The only kernel code that does rely on LogInstance() is certain low level code in
the util library, like the RNG seeder, that is not passed a specific instance
and needs to rely on the global LogInstance() function.

Other code outside the kernel library uses LogInstance() heavily, and may
continue to do so. bitcoind and test code now just create a log instance before
the first LogInstance() call, which it returns, so all behavior is the same as
before.
ryanofsky added a commit to ryanofsky/bitcoin that referenced this pull request Dec 12, 2025
Current kernel logging API is too complicated and too restrictive. This PR
tries to improves it.

I'd expect an API that supported logging to allow creating log streams with
different options and providing some way to specify which library operations
should be logged to which streams.

By contrast, the current API allows creating multiple log streams, but all the
streams receive the same messages because options can only be set globally and
the stream objects can't be passed to any kernel API functions. They are not
even referenced by the `btck_Context` struct which holds other shared state. If
no log streams are created, log messages are generated anyway, but they are
stored in a 1MB buffer and not sent anywhere, unless a log stream is created
later, at which point they are sent in bulk to that stream. More log streams
can be created after that, but they only receive new messages, not the buffered
ones. If log output is not needed, a btck_logging_disable() call is required to
prevent log messages from accumulating in the 1MB buffer. Calling this will
abort the program if any log streams were created before it was called, and
also abort the program if any new log streams are created later.

None of these behaviors seem necessary or ideal, and it would be better to
provide a simpler logging API that allows creating a log stream, setting
options on it, registering it with the `btck_Context` instance and receiving
log messages from it. Another advantage of this approach is that it could allow
(with bitcoin#30342) different log streams to be used for different purposes, which
would be not be possible with the current interface.
ryanofsky added a commit to ryanofsky/bitcoin that referenced this pull request Dec 12, 2025
Allow LogDebug(), LogTrace(), LogInfo(), LogWarning(), and LogError() macros to
accept context arguments to provide more information in log messages and more
control over logging to callers.

This functionality is used in followup PRs:

- bitcoin#30342 - To let libbitcoinkernel send
  output to specfic `BCLog::Logger` instances instead of a global instance, so
  output can be disambiguated and applications can have more control over
  logging.

- bitcoin#30343 - To replace custom
  `WalletLogPrintf` calls with standard logging calls that automatically include
  wallet names and don't log everything at info level.

This commit does not change behavior of current log prints or require them to
be updated. It includes tests and documentation covering the new functionality.

Co-Authored-By: Hodlinator <[email protected]>
@DrahtBot
Copy link
Contributor

🚧 At least one of the CI tasks failed.
Task ASan + LSan + UBSan + integer: https://github.com/bitcoin/bitcoin/actions/runs/20166570929/job/57895220709
LLM reason (✨ experimental): CTest failure: test_kernel failed (exit code 8) causing the CI 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.

@DrahtBot
Copy link
Contributor

🐙 This pull request conflicts with the target branch and needs rebase.

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

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants