Skip to content

logging: streamline Logger state and drop redundant methods - #35322

Open
ryanofsky wants to merge 13 commits into
bitcoin:masterfrom
ryanofsky:pr/levels
Open

ryanofsky wants to merge 13 commits into
bitcoin:masterfrom
ryanofsky:pr/levels

Conversation

@ryanofsky

@ryanofsky ryanofsky commented May 19, 2026 •

Copy link
Copy Markdown
Contributor

Problem: The Logger class currently tracks enabled log messages using three separate fields:

  • m_categories — bitmask of enabled log categories
  • m_log_level — global log level threshold
  • m_category_log_levels — hash map of per-category level overrides

This representation is confusing and redundant. Bitcoin Core has only ~30 log categories and 2 conditional log levels, so a mutex-protected hash map, a bitset, and a separate global level are unnecessary. The added complexity is also harmful: it makes the code harder to follow, and basic operations like setting a category's level require coordinating multiple fields and method calls.

Solution: This PR streamlines the Logger class without changing behavior, replacing the three fields with two atomics: one bitmask for each conditional log level (Debug and Trace). Each bitmask records which categories are enabled at that level.

This allows the following methods to be dropped: EnableCategory, DisableCategory, WillLogCategory, LogLevel, SetLogLevel, GetCategoryMask, AddCategoryLogLevel. The remaining SetCategoryLogLevel and WillLogCategoryLevel methods are now self-contained.

Behavior note: This is a behavior-preserving refactor with one exception: categories dynamically enabled at runtime through the logging RPC or the kernel btck_logging_* API are now always enabled at Debug level, even if -loglevel=trace or its kernel equivalent was set at startup. This is unlikely to matter in practice. Very little LogTrace logging currently exists, and both APIs are being reworked in #34038 and #34374. The -loglevel option otherwise continues to work as before when categories are not changed at runtime.

@DrahtBot

DrahtBot commented May 19, 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.
A summary of reviews will appear here.

Conflicts

Reviewers, this pull request conflicts with the following ones:

  • #35387 (logging: make trace logging easily usable by ryanofsky)
  • #35355 (Use atomics for determining whether trace logging is enabled by ajtowns)
  • #34778 (logging: rewrite macros to enforce restrictions at compile-time, improve efficiency and usability by ryanofsky)
  • #34038 (logging: replace -loglevel with -trace, expose trace logging via RPC by ajtowns)
  • #29256 (log, refactor: Allow log macros to accept context arguments by ryanofsky)
  • #17783 (common: Disallow calling IsArgSet() on ALLOW_LIST options by ryanofsky)
  • #17580 (refactor: Add ALLOW_LIST flags and enforce usage in CheckArgFlags 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.

Comment thread src/test/logging_tests.cpp Resolved

@l0rinc l0rinc 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.

I tried splitting this locally to make review easier. I still think the current version mixes several separate concerns, and I have questions about whether grouping levels and categories this way is the right model, since it seems to apply a general rule to behavior that is currently quite specific and ad hoc.

Left comments on splitting the commit into smaller reviewable steps, clarifying or preserving behavior changes, and adding focused tests for intentional changes.

Main concerns are startup/kernel logging semantics, runtime-enable behavior coverage, and making the new m_levels model easier to reason about.

Comment thread src/test/logging_tests.cpp Resolved
Comment thread src/test/logging_tests.cpp Resolved
Comment thread src/logging.h Resolved
Comment thread src/logging.cpp Resolved
Comment thread src/test/logging_tests.cpp Outdated
const auto net_it{category_levels.find(BCLog::LogFlags::NET)};
BOOST_REQUIRE(net_it != category_levels.end());
BOOST_CHECK_EQUAL(net_it->second, BCLog::Level::Trace);
BOOST_CHECK(LogInstance().WillLogCategoryLevel(BCLog::NET, BCLog::Level::Trace));

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.

Isn’t this a behavior change?

Previously, setting a category level at startup stored the override, but it had no visible effect unless the category was also enabled with -debug.
Here, setting -loglevel=net:trace appears to enable net by itself.

@ryanofsky ryanofsky May 27, 2026 •

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.

re: #35322 (comment)

Isn’t this a behavior change?

Yes, nice catch! I do think this behavior change is good, but it wasn't intended to be part of this PR. It's fixed by making -loglevel only update the levels of previously enabled categories.

Edit: To follow up, I should add a test to make sure a standalone -loglevel option without -debug continues to be ignored.

Comment thread src/logging.cpp Resolved
Comment thread src/logging.cpp Resolved
Comment thread src/rpc/node.cpp
if (!flag) {
throw JSONRPCError(RPC_INVALID_PARAMETER, "unknown logging category " + cat);
}
LogInstance().SetCategoryLogLevel(*flag, enable ? BCLog::Level::Debug : BCLog::Level::Info);

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.

Could we add a test that goes through this runtime-enable path after startup configured the category at Trace?

The PR description notes that runtime enables now use Debug even if startup used Trace. A test through the RPC/kernel entry point would make that intentional behavior change easy to verify.

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.

re: #35322 (comment)

Could we add a test that goes through this runtime-enable path after startup configured the category at Trace?

The PR description notes that runtime enables now use Debug even if startup used Trace. A test through the RPC/kernel entry point would make that intentional behavior change easy to verify.

Yes this is a good idea. Current PR doesn't add new tests but it should and I will follow up with this.

Comment thread src/rpc/node.cpp Resolved
Comment thread src/kernel/bitcoinkernel.cpp Outdated
}

LogInstance().AddCategoryLogLevel(get_bclog_flag(category), get_bclog_level(level));
LogInstance().SetCategoryLogLevel(get_bclog_flag(category), get_bclog_level(level));

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.

This looks similar to the earlier concern. Isn't this a behavior change as well? Previously, setting a category level did not enable the category. Now it looks like setting the level also enables it. Should we adjust this to match the old behavior?
I see the tests don't always keep the enable-first-set-level after, but maybe we can do that:

diff --git a/src/test/kernel/test_kernel.cpp b/src/test/kernel/test_kernel.cpp
--- a/src/test/kernel/test_kernel.cpp	(revision 06d9f340624c880883fba2b03aeab1b74d8812a8)
+++ b/src/test/kernel/test_kernel.cpp	(revision c9516e72f9c26f76aacc510e9d39448291fc2994)
@@ -636,6 +636,7 @@
     };
 
     logging_set_options(logging_options);
+    logging_enable_category(LogCategory::BENCH);
     logging_set_level_category(LogCategory::BENCH, LogLevel::TRACE_LEVEL);
     logging_disable_category(LogCategory::BENCH);
     logging_enable_category(LogCategory::VALIDATION);
@@ -643,8 +644,8 @@
 
     // Check that connecting, connecting another, and then disconnecting and connecting a logger again works.
     {
-        logging_set_level_category(LogCategory::KERNEL, LogLevel::TRACE_LEVEL);
         logging_enable_category(LogCategory::KERNEL);
+        logging_set_level_category(LogCategory::KERNEL, LogLevel::TRACE_LEVEL);
         Logger logger{std::make_unique<TestLog>()};
         Logger logger_2{std::make_unique<TestLog>()};
     }

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.

re: #35322 (comment)

This looks similar to the earlier concern. Isn't this a behavior change as well?

Yes this analogous to the other change you pointed out #35322 (comment).

In this case I think the new behavior is probably better as there is no point to kernel code setting a level for a category that is ignored because the category is enabled. (For bitcoind it might have made sense previously because logging RPC is more limited than the kernel API.)

But this behavior change should be documented and tested, so I will try to add your test suggestion and follow up.

@ryanofsky

Copy link
Copy Markdown
Contributor Author

Rebased ccd90a7 -> a76b137 (pr/levels.1 -> pr/levels.2, compare) due to conflict with #34806

@DrahtBot

Copy link
Copy Markdown
Contributor

🚧 At least one of the CI tasks failed.
Task Windows-cross to x86_64, msvcrt: https://github.com/bitcoin/bitcoin/actions/runs/26472785758/job/77960548589
LLM reason (✨ experimental): CI failed due to a C++ build error in src/init/common.cpp: GetLogCategory is not declared (missing/renamed logging helper).

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.

@ryanofsky ryanofsky 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.

Thanks for the review! PR is now split up instead of being a single commit and I implemented most suggestions, but need to follow up on the ideas for adding more tests. (EDIT: tests are added now)

Updated a76b137 -> 30cb9ee (pr/levels.2 -> pr/levels.3, compare) with review suggestions

Updated 30cb9ee -> dd4b33e (pr/levels.3 -> pr/levels.4, compare) adding new tests commits before changes to cover more behaviors, also making other small cleanups

Updated dd4b33e -> 70b4bee (pr/levels.4 -> pr/levels.5, compare) to fix CI link errors: LogInstance() hidden by REDUCE_EXPORTS=ON; override visibility for logging.cpp in kernel build https://github.com/bitcoin/bitcoin/actions/runs/26643504769/job/78546254795

Updated 70b4bee -> be5e736 (pr/levels.5 -> pr/levels.6, compare) to fix Windows DLL link errors in test_kernel https://github.com/bitcoin/bitcoin/actions/runs/26787798064/job/78967518054

Updated be5e736 -> 395473b (pr/levels.6 -> pr/levels.7, compare) to fix Windows cross CI: --export-dynamic-symbol and -fvisibility=default are ELF-only; use .def file to export logging symbols from DLL https://github.com/bitcoin/bitcoin/actions/runs/27141219495/job/80118211985

Rebased 395473b -> faf4496 (pr/levels.7 -> pr/levels.8, compare) due to conflicts with #35182 and #34051

Squashed faf4496 -> d03bc91 (pr/levels.8 -> pr/levels.9, compare) to fix CI: hardcoded category count in logging_Conf test (29 != 30) in intermediate commit failing in ancestor commits job https://github.com/bitcoin/bitcoin/actions/runs/28106965454/job/83223705517 due to LIBEVENT removal

Squashed d03bc91 -> 42d98b7 (pr/levels.9 -> pr/levels.10, compare) to fix ancestor commits job https://github.com/bitcoin/bitcoin/actions/runs/28115551994/job/83254010233 failing due to intermediate commits accidentally squashed and moved in previous push

Rebased 42d98b7 -> addaf64 (pr/levels.10 -> pr/levels.11, compare) due to conflicts with #34465 and #35597

Rebased addaf64 -> a73d23b (pr/levels.11 -> pr/levels.12, compare) due to conflict with #35205

Rebased a73d23b -> 3ffb46f (pr/levels.12 -> pr/levels.13, compare) due to conflict with #36275

Updated 3ffb46f -> 22d0bc8 (pr/levels.13 -> pr/levels.14, compare) to fix iwyu errors https://github.com/bitcoin/bitcoin/actions/runs/36794620285/job/110155093409

Rebased 22d0bc8 -> d5df90e (pr/levels.14 -> pr/levels.15, compare) due to conflicts with #34374 and #34729, dropping the "logging test: add behavior assertions to kernel logging_tests" commit because #34374 removed the kernel logging API it tested

Comment thread src/test/logging_tests.cpp Resolved
Comment thread src/test/logging_tests.cpp Resolved
Comment thread src/logging.h Resolved
Comment thread src/logging.cpp Resolved
Comment thread src/test/logging_tests.cpp Outdated
const auto net_it{category_levels.find(BCLog::LogFlags::NET)};
BOOST_REQUIRE(net_it != category_levels.end());
BOOST_CHECK_EQUAL(net_it->second, BCLog::Level::Trace);
BOOST_CHECK(LogInstance().WillLogCategoryLevel(BCLog::NET, BCLog::Level::Trace));

@ryanofsky ryanofsky May 27, 2026 •

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.

re: #35322 (comment)

Isn’t this a behavior change?

Yes, nice catch! I do think this behavior change is good, but it wasn't intended to be part of this PR. It's fixed by making -loglevel only update the levels of previously enabled categories.

Edit: To follow up, I should add a test to make sure a standalone -loglevel option without -debug continues to be ignored.

Comment thread src/logging.cpp Resolved
Comment thread src/logging.cpp Resolved
Comment thread src/rpc/node.cpp
if (!flag) {
throw JSONRPCError(RPC_INVALID_PARAMETER, "unknown logging category " + cat);
}
LogInstance().SetCategoryLogLevel(*flag, enable ? BCLog::Level::Debug : BCLog::Level::Info);

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.

re: #35322 (comment)

Could we add a test that goes through this runtime-enable path after startup configured the category at Trace?

The PR description notes that runtime enables now use Debug even if startup used Trace. A test through the RPC/kernel entry point would make that intentional behavior change easy to verify.

Yes this is a good idea. Current PR doesn't add new tests but it should and I will follow up with this.

Comment thread src/rpc/node.cpp Resolved
Comment thread src/kernel/bitcoinkernel.cpp Outdated
}

LogInstance().AddCategoryLogLevel(get_bclog_flag(category), get_bclog_level(level));
LogInstance().SetCategoryLogLevel(get_bclog_flag(category), get_bclog_level(level));

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.

re: #35322 (comment)

This looks similar to the earlier concern. Isn't this a behavior change as well?

Yes this analogous to the other change you pointed out #35322 (comment).

In this case I think the new behavior is probably better as there is no point to kernel code setting a level for a category that is ignored because the category is enabled. (For bitcoind it might have made sense previously because logging RPC is more limited than the kernel API.)

But this behavior change should be documented and tested, so I will try to add your test suggestion and follow up.

@DrahtBot

DrahtBot commented Oct 1, 2026

Copy link
Copy Markdown
Contributor

🚧 At least one of the CI tasks failed.
Task iwyu: https://github.com/bitcoin/bitcoin/actions/runs/36794620285/job/110155093409
LLM reason (✨ experimental): CI failed because iwyu reported an include-issues failure (it edited files and the script intentionally returned non-zero: “Failure generated from IWYU”).

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.

ryanofsky and others added 13 commits October 29, 2026 10:45
Currently there are no tests checking behavior of -loglevel and -debug options
together, even though they need to be used together for -loglevel to have any
visible effect. This commit extends -loglevel unit tests to check its behavior
with and without -debug.

Background: Using the -loglevel option alone has no effect on log output,
because it only assigns log levels (info/debug/trace) to categories, but
doesn't "enable" the categories, It needs to be combined with -debug which does
enable them to take effect. (There are reasons to want to change this behavior,
see bitcoin#35387, but changing it is beyond the scope of this PR.) The
point of this commit to extend the test to provide meaningful coverage for
subsequent commits.

In addition to adding -debug arguments, make the following test improvements:

- Add `init::SetLoggingCategories` calls needed to parse -debug options

- Replace const char*[] variables with std::array to avoid needing to hardcode
  parameter counts.

- Drop unused result variables

- Check WillLogCategoryLevel results to verify -loglevel settings actually
  have expected impact on what is logged and not logged.

- Replace -loglevel=debug options with -loglevel=trace options. Passing
  -loglevel=debug is somewhat pointless because the default global log level is
  already -debug.

This change was written with Claude Sonnet 4.6.
…m_levels array

Replaces three separate private fields with a single array of atomic
category bitmasks indexed by log level:

  std::array<std::atomic<CategoryMask>, 2> m_levels;

Each category now has a single level threshold (Trace, Debug, or Info),
eliminating the separate enabled/disabled flag and stored global log level.
This reduces the number of possible states, removes mutex locking and hash
lookups from log-level checks, and simplifies the Logger interface by
dropping multiple enable, disable, and query methods that are no longer
necessary.

This is mostly a behavior-preserving refactor. The one exception is that
categories enabled at runtime via the `logging` RPC are now always enabled
at debug level, regardless of whether `-loglevel=trace` is set. The kernel
logging API (`btck_logging_*`) has analogous behavior changes for the same
reason. This is unlikely to matter in practice: very little LogTrace logging
exists, and both APIs are being reworked (bitcoin#34038 and
bitcoin#34374). The `-loglevel` setting otherwise continues to work
exactly as before when categories are not changed at runtime.

Old methods (EnableCategory, DisableCategory, WillLogCategory,
GetCategoryMask, CategoryLevels, AddCategoryLogLevel, SetCategoryLogLevel
overloads, LogLevel, SetLogLevel, DefaultShrinkDebugFile) are kept as
backward-compatible wrappers and will be removed in subsequent commits.

This change was written with Claude Sonnet 4.6.
This commit does not change behavior in any way.

Co-authored-by: l0rinc <[email protected]>
This change was written with Claude Sonnet 4.6.
…Level

This commit does not change behavior in any way.

This change was written with Claude Sonnet 4.6.
…gEnabled()

This commit does not change behavior in any way.

This change was written with Claude Sonnet 4.6.
This commit does not change behavior in any way.

This change was written with Claude Sonnet 4.6.
This change was written with Claude Sonnet 4.6.
This change was written with Claude Sonnet 4.6.
This commit does not change behavior in any way.

This change was written with Claude Sonnet 4.6.
This commit does not change behavior in any way.

This change was written with Claude Sonnet 4.6.
This commit does not change behavior in any way.

This change was written with Claude Sonnet 4.6.
This commit does not change behavior in any way.

This change was written with Claude Sonnet 4.6.
This commit does not change behavior in any way.

This change was written with Claude Sonnet 4.6.
@DrahtBot

Copy link
Copy Markdown
Contributor

🚧 At least one of the CI tasks failed.
Task 32 bit ARM: https://github.com/bitcoin/bitcoin/actions/runs/41053854619/job/124056320251
LLM reason (✨ experimental): CI failed because CTest tried to execute ARM-built test binaries on the host, producing shell syntax errors in four tests.

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.

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

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants