mirror of
https://github.com/bitcoin/bitcoin
synced 2026-12-04 10:50:37 +00:00
kernel: use struct-based logging and simplify logging interface #34374
Labels
No labels
Android
Backport
Block storage
Brainstorming
Bug
Build system
CI failed
Consensus
Data corruption
Descriptors
Docs
DrahtBot Guix build requested
Feature
Fuzzing
GUI
Good First Review
IPC
Insufficient Review
Kernel
Linux/Unix
Mempool
Mining
Needs Backport (31.x)
Needs Backport (32.x)
Needs Benchmark
Needs Conceptual Review
Needs backport (30.x)
Needs rebase
Needs release note
Net
P2P
PSBT
Privacy
Private Broadcast
Questions and Help
RPC/REST/ZMQ
Refactoring
Resource usage
Review club
Scripts and tools
Settings
TX fees and policy
Tests
Tracking Issue
UTXO Db and Indexes
Up for grabs
Upstream
Utils/log/libs
Validation
Waiting for author
Wallet
Windows
good first issue
interfaces
macOS
No milestone
No project
No assignees
2 participants
Notifications
Due date
No due date set.
Dependencies
No dependencies set
Reference
bitcoin/bitcoin!34374
Loading…
Reference in a new issue
No description provided.
Delete branch "2026-01/kernel-logging-layering-predicate"
Deleting a branch is permanent. Although the deleted branch may continue to exist for a short time before it actually gets removed, it CANNOT be undone in most cases. Continue?
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
bitcoinkernellibrary (#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:
btck_logging_set_level_categoryandbtck_logging_enable_categorywhen they want to producedebugortracelogs. 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.Approach
Log generation (
util/log.h: macros,util::log::Entry, and theShouldDebugLog/ShouldTraceLog/Loghooks an application must provide) was already separated from log handling (logging.h) in #34465 and subsequent PRs. This PR givesbitcoinkernelits own implementation of those hooks, so it no longer depends onlogging.cpp, and upgrades the C API to deliver struct-based entries. Node logging is not changed.WARNING,ERROR,TXPACKAGES,LOCK) and thebtck_LogEntrystruct, addName()helpers to the C++ wrapper, and removebtck_logging_set_optionsandbtck_logging_disable(with struct-based entries there is no kernel-side format to configure, and without buffering there is nothing to disable).KernelLogger: a kernel-owned backend that holds the registered callbacks and the minimum level, and converts eachutil::log::Entryinto abtck_LogEntry. Introduced in a separate commit to keep the scope of the behaviour-changing commit smaller.btck_LogCallbackreceives abtck_LogEntryinstead of a string, theutil::loghooks are implemented onKernelLogger,logging.cppis dropped from the kernel build, and the logging configuration interface is reduced tobtck_logging_set_min_level().Behaviour changes for consumers (also described in each commit message):
Infoand above.Debug/Traceapply to all categories, consumers can filter onbtck_LogEntry::category(but string formatting is done for the entire level, instead of per enabled category).Appendix
bitcoinkernelC logging interfaceThe 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.
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:
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.
🚧 At least one of the CI tasks failed.
Task
tidy: https://github.com/bitcoin/bitcoin/actions/runs/21223722631/job/61065673932LLM 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.
This seems like a regression. With this approach you can't assume
LogInfocalled during global initialization won't be called prior toInitLogger(), as it now only needs to pass throughGetDispatcher()andg_dispatcher().As far as I can see,
g_dispatcher()should just have independent implementations for bitcoin-kernel vs bitcoind, bitcoin-qt, bitcoin-cli etc.Jumping through a
std::functionwhen we could just be checking an atomic bitfield doesn't seem like a good approach.I think that's only possible if we either 1) have
util::log::Dispatcherexpose all ofBCLog::Logger's category/level setting logic, or 2) makeDispatcher::WillLogvirtualand let each logging sink create its ownDispatchersubtype. Were you thinking of another approach?I don't think either approach is warranted to justify the minimal overhead that
std::functionincurs. 1) would just makeDispatcher's scope way too big in my view, and 2) would require inheritance and still have some (although probably less) overhead from the virtual table lookup.Yes, I think that's a much better approach, thanks for the suggestion. I'll incorpocate that and update shortly.
I think it should suffice to declare
g_dispatcher()inutil/log.h, and have one implementation inbitcoinkernel.cpp, and one inlogging.cpp(which just callsLogInstance().GetDispatcher()). All non-kernel binaries can (at least for now) just use the same implementation, I think? Lmk if I'm misunderstanding something.🚧 At least one of the CI tasks failed.
Task
iwyu: https://github.com/bitcoin/bitcoin/actions/runs/21368395725/job/61506234805LLM reason (✨ experimental): IWYU reported include-what-you-use changes and caused the CI step 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.
Force-pushed to:
SetDispatcherandGetDispatcherand instead implemented differentg_dispatcherfunctions forlogging.cppandbitcoinkernel.cpp. This required quite a bit of code re-organization, including splitting out the kernel API changes into multiple commits (one for structured logging, one for levels-based filtering) - which I think improve the overall commit organization, but will make range-diff reviews pretty hard for this force-push.BCLog::Logger::Enabled()in thefilterfunctionI've changed the approach to your suggestion, so marking this as resolved.
I doubt that there is an actual use case for multiple logging connections. The logger is global internally and can be handled as global by clients as well (no need for userdata). Consider modelling the logging API after set_terminate in the C++ standard library:
I also think that clients are able to apply their own filtering, so the
btck_logging_set_min_levelfunction can be removed. It is worth noting that this function was never designed to filter per-connection, which was leaking the implementation detail that the logger is global.I interpret that as "We have to use a singleton here because of other singletons".
Now everybody should understand why singletons are viral and therefore should be forbidden. I have zero tolerance for such code.
I'm sorry to hear. What do you suggest as an alternative?
I think this concern is orthogonal to the changes proposed in this PR, so I think that conversation might be better had e.g. in #30342 ?
They are, but I think it's reasonable to offer a (minimal) way for clients to avoid paying for overhead (mostly string formatting, lambda evaluation, and expensive operations like memory usage calculations) for logs from levels that will be dropped anyway. Keeping this as-is for now, happy to reconsider if this is a general point of contention.
I don't know that
Dispatcherneeds to make the category/levels modifiable -- that seems like something theg_dispatcherimplementation could handle via marking them asprotectedinDispatcher. They should be directly testable via Dispatcher, so that disabled debug/trace categories are trivial to test, without needing indirection.I think your latest implementation (a4e8f3c8d6763a95c1804fc40781b379e6127b66) is dangerously wrong, btw --
LogInfo()etc currently always evaluate their arguments, whereas you're making that conditional onLogAcceptCategorywhich callsWillLogwhich is conditional onEnabled().I didn't realize
developer-notes.mdsays to only avoid relying on side-effects forLogDebugandLogTrace, I thought this was true for logging in general. I think it's very brittle that program execution potentially relies on side-effects in logging statements, and I think we should move away from that completely. A cursory search didn't show me any{Info,Warning,Error}statements that have such side-effects, but I agree that it's possible and that makes reviewing this PR much more difficult, so I'll revert that behaviour to minimize scope and leave room for a follow-up. Thanks for pointing this out.I'm not sure I understand your concern here. They are testable via
Dispatcher::WillLog(). Is it purely the indirection performance overhead you're worried about? When running the benches on main and on a4e8f3c8d6763a95c1804fc40781b379e6127b66 (with small change to runthis->Enabled()afterthis->WillLogCategoryLevel(static_cast<BCLog::LogFlags>(cat), level)which I'll include in next force-push, it doens't look like we have anything to worry about?On master (
34a5ecadd7):On a4e8f3c8d6763a95c1804fc40781b379e6127b66 (with small unpushed modification):
Latest force-push (dca56e0237abb485edd1cfe870069e2d75f08e42) reverts the unconditional argument evaluation for
Infoand higher levels, and adds a unit test to ensure behaviour before and after this PR remains the same. Thanks for raising this. Would be nice to remove logging side-effects entirely in a follow-up (probably just a documentation change and maybe some fix-ups).Latest force-push:
Infoand higher levels, and adds a unit test to ensure behaviour before and after this PR remains the same. Addresses @ajtown's comment.BCLog::Logger's callback now first evaluatesWillLogCategoryLevel()before verifying the logger isEnabled(), so we can keep the operation lock-free when the category isn't disabled. No behaviour change, just a small optimization.🚧 At least one of the CI tasks failed.
Task
iwyu: https://github.com/bitcoin/bitcoin/actions/runs/21445810981/job/61765316670LLM reason (✨ experimental): IWYU failure: include-what-you-use detected issues and exited non-zero.
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.
Code review a4e8f3c8d6763a95c1804fc40781b379e6127b66. Major concept and approach ACK. This seems thoughtfully implemented to be minimally disruptive to existing code while rationalizing the kernel logging API:
set_optionsfunction with obscure options likelog_time_micros.set_level_categoryenable_categorydisable_categorythat can interact in unexpected ways. Just providing basic level filtering, while leaving space to add other filtering options later.logging_disablefunction that needs to be called by applications that don't use logging. (Note: #33847 also eliminates this).Suggestion to remove extra overhead
I do agree with AJ that requiring a call through a function pointer https://github.com/bitcoin/bitcoin/pull/34374#discussion_r2720709919 just to detect whether to log something does not seem good. Fortunately, there should be no need to do this for bitcoin core logging, though we may want to preserve it as an option for kernel logging. a4e8f3c8d6763a95c1804fc40781b379e6127b66 already has a statically linked
g_dispatcher()function with different implementations inkernel/bitcoinkernel.cppandlogging.cpp, so it would only need to add a secondg_dispatcher_should_loghook, defined differently for kernel and non-kernel binaries to avoidstd::functionoverhead:diff
(Note: this could be rearranged and simplified more, it is just meant to provide a minimal change to consider.)
Suggestion to split up PR
My main feedback on the PR is that it is making a lot of trivial / move-only changes that I think would be better to move to a base PR:
SourceLocationfromlogging.htoutil/log.h(base PR could introduceutil/log.h)BCLog::Levelfromlogging.htoutil/log.hThese are all worthwhile changes on their own, and moving them out of this PR should make it substantially smaller and easier to navigate.
I plan to review this PR more and also rebase #30342 on top of this. I think the PR's should complement each other well.
Thanks for the in-depth review and suggestions, @ryanofsky !
I hadn't considered this approach yet, and I think it's great. If we already have a
g_should_log()global hook, I think it makes more sense to just scrap the filtering fromDispatcherentirely and let the user manage it completely. This simplifies the code, improves performance (e.g. if filtering is already done before arg evaluation, it doesn't have to be done again before dispatching) and avoids the pattern of havingDispatcherinstances opaquely call a global function, when users would probably expect it to be local.I've adopted some of your carve-out suggestions, and identified a few other places to make commits more straightforward. I prefer bundling (manageable) amount of clean-up with an actual functional improvement, so I'll open up a new PR that introduces the struct-based logging (i.e. the first commits), and convert this (now draft) follow-up PR to be about levels-based logging and removing
logging.cppfromkernel.Your approach sounds reasonable. That said, I think it would be nice to first disentangle the move-only changes and make an initial PR that simply moves the log-emitting code from
logging.htoutil/log.h(logging macros, level and category constants,SourceLocation,LogAcceptCategory). This could likely be merged quickly, making the more substantive changes that follow easier to review.This also makes sense conceptually: log-emitting and log-handling are separate concerns, and there’s no real reason code that only emits log messages should need to include a header defining a full log management API.
Another selfish reason I have for preferring the move-only changes first is that it should significantly reduce conflicts between your changes and my existing PRs, and make it easier to combine my logging work with yours.
re: https://github.com/bitcoin/bitcoin/pull/34374#issuecomment-3824030533
I implemented this in #34465 (after chatting with stickies in IRC). The changes in the first 4 commits were taken directly from this PR. Only the last commit adds a bit of new code.
The easiest way to ensure any potential/accidental side-effects don't make the behaviour brittle is to always evaluate the logging statements, which is what our code currently does -- it's similar logic as always evaluating assertions. Changing that is not a nice follow-up.
🐙 This pull request conflicts with the target branch and needs rebase.
Hi stickies, it'd be really nice to have this rebased & start review. Here is a rebase branch I made: https://github.com/ryanofsky/bitcoin/commits/review.34374.2-edit with minimal changes.
There are more simplifications that can be made, but it's already much smaller and simpler after #34465
Apologies for the slow follow-up here @ryanofsky. My priorities were elsewhere for a while, but I've now picked this up again.
Since we now have the
{Should}Loginterface inutil/log.h, I think also havingutil::log::Dispatcherdoesn't really make sense anymore, so I've been reworking that into a kernel-specific type that implements the{Should}Loginterface. I've been looking at a couple of different approaches and commit orderings to make reviewing as smooth as possible and think I'm close to having a good solution.FWIW I did this in the linked branch:
github.com/bitcoin/bitcoin@8611ff533c/src/kernel/bitcoinkernel.cpp (L85-L93)The Dispatcher type is kernel-specific there and not used outside the kernel. The only thing I didn't do was move the dispatcher class definition and strip out some unused code because I was avoiding extraneous changes in the rebase. Seems fine to reimplement, though. Should be equivalent to using the branch and the stripping bits of code that are no longer needed.
Here is a rebased version of this PR with the logger cleanups from #34865 dropped: ec9e622d2da96ac482cf1bf599e20292d2f78759 (branch)
Now there's basically no overlap between this PR and #34865 so both could be reviewed in parallel.
Aside from the logger change I also dropped some dead code in the dispatcher class from the previous rebase and rewrote one commit message. Otherwise the branch is unchanged and the commits are straightforward:
Here is a rebased version of this pr: 683056775c58f05f9603f3f7023467ab0e7f723e (branch) again with minimal changes from the original.
I'd really like to review and be able to merge this change because it makes the kernel logging API simpler and more usable.
When I rebased this, I made as few changes as possible so comparison to the current version would be simple. But there are a few additional cleanups that could be made on top of this:
Dispatcherclass should probably be moved out ofutil/logsince dispatching is a log-handling function not a log-generating function. As mentioned https://github.com/bitcoin/bitcoin/pull/34865#issuecomment-4236420269, theDispatcherclass could also be dropped and replaced with a btcsignals::signal. But it is a very simple class so it seems fine to keep.A few simplifications / renames in
bitcoinkernel.cppwould probably be appropriate like inliningg_dispatcher. I just kept current names for things so diffs would be minimal.⌛ There hasn't been much activity lately and the patch still needs rebase. What is the status here?
🚧 At least one of the CI tasks failed.
Task
lint: https://github.com/bitcoin/bitcoin/actions/runs/34283939029/job/102254999690LLM reason (✨ experimental): CI failed because the lint check detected a new circular dependency:
kernel/bitcoinkernel -> kernel/logger -> kernel/bitcoinkernel(lint-circular-dependencies).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.
Apologies for the months of radio silence here. I've had many cycles of exploring various architectures and ways to minimize review burden, to then kind of get stuck on something I really didn't like, give up, and repeat a while later. While I've found pretty much every approach to have its own downsides, I believe the current version has the best set of trade-offs.
kernelandnodelogging having to co-exist complicates many things, but is a reality we have to work around.The main changes in this latest version are:
masterutil::log::Dispatcheris gone. Instead, this PR implements theLogandShould{Debug,Trace}Loginterface, and removes thestd::functionindirection callbacks this PR used to have. The newKernelLoggerthat keeps state (minimum level and callbacks) is small and kernel-specific, and an implementation detail.mocktimeis added tobtck_LogEntrybtck_log_level_get_name/btck_log_category_get_nameC functions from the earlier version; the C++ wrapper hasName()helpers instead. Consumers know the constants, so I don't think this belongs in the C API. It removes a lot of the churn in the previous approach wrt using arrays for the btck/util/name mapping.Assume). We can't currently enforce a complete mapping at compile time, and it's fairly easy for a new category to accidentally slip into kernel code. If that's in a rare code path, it'd be dangerous for that to crash in non-debug builds.Thoughts on things I've explored:
util::loginterface requires exactly one implementation, certain gradual changes are not really possible without workarounds that then add review complexity.util::logneeds exactly one implementation per binary,test_bitcoincan't link the kernel library, andtest_kernelonly sees the exported C API, soKernelLoggerisn't reachable from either test binary without workarounds. I've tried movingKernelLoggerinto its own header sotest_bitcoincan compile it directly. That runs into the circular dependency linter and, when header-only, into clang's-Wunique-object-duplicationfor the singleton. Working around that means moving the logging C functions out ofbitcoinkernel.cppand sharing theHandletemplate through yet another header, which is even more churn. I think we should improve this through https://github.com/bitcoin/bitcoin/pull/28690 and then a new organization of test binaries (e.g. test_node, test_kernel, and test_kernel_interface), but I'm very hesitant to add that to the scope of this PR, which I feel is already fairly large.Despite my hesitations, I think these changes would massively improve the kernel logging interface, and help with better separation between
kernelandnode.Marking this as resolved, as the PR has changed a lot since then and the conversation no longer applies I think. The indirection is gone, and this PR now doesn't touch util/node logging (including logging statement evaluation) at all (except for a documentation change). Happy to re-open if I've missed anything.
RegisterCallback()andLogDebug()can also throwstd::bad_alloc.btck_LoggingConnectioncan be a smart pointer. Holding the connection in astd::unique_ptrprevents its allocation from leaking if logging throws.Shouldn't
user_databe destroyed if the callback registration fails ?Good point, thanks. I think
btck_logging_connection_destroyalso needs similar improvements.Fixed by wrapping user data in a RAII
UserDatawrapper, and the callback in a RAIICallbackHandlewrapper. It's a larger diff, but I think it makes for cleaner code. TheUserDatacan be reused in other places too, but I'd prefer doing that in a follow-up as it's unrelated to this change. Does this address your concern? You're right thatLogDebugalso could potentially throw, but this is true in the bitcoinkernel code in general and I feel might be out of scope here?Force-pushed to wrap user data and the callbacks in RAII wrappers, addressing @w0xlt's comment and making it harder to introduce similar issues in the future. Also moved
KernelLoggerinto the anonymous namespace in the final commit.Force-pushed to address merge conflict with #36207, no other changes.
There is a narrow failure case here, related to the concerns about callbacks running under locks discussed in #36197.
Registration creates a temporary
Callbackwhile holding the logger mutex. That temporary ownsuser_data. If allocating the list node throwsstd::bad_alloc, the temporary is destroyed before the mutex is released, invokinguser_data_destroy_callback.If that callback destroys another logging connection, it tries to acquire the same mutex and deadlocks, preventing
btck_logging_connection_createfrom returningnullptr.Suggestion: the callback can be constructed before the lock guard, so exception cleanup releases the mutex before destroying the user data, consistent with
UnregisterCallback.Good catch, fixed. You're right to point out we need to be careful with executing callbacks when under a lock. I think we should work to making
Logexecute the logging callbacks without lock too, but I think that's best kept for a follow-up.Even worse, it can be triggered if the callback interacts in any way with the logger, including producing a logging statement. (edit: of course, this is still a very narrow failure case, requiring allocation failure and an I think unusual path where cleaning up user data interacts with the kernel).
Force-pushed to address a (hard to reach) deadlock issue flagged by @w0xlt
ACK
cfd2312f0fCode review ACK
cfd2312f0f. Thanks for the nice updates! Droppingutil::log::Dispatcherand implementing the log hooks directly inKernelLoggeris simpler than routing through a dispatcher that only ever has one implementation per binary, and struct-based entries plus level-only filtering are a good simplification of the API.I left some comments below, but they are all minor or just notes, and none are blocking.
In commit "kernel: make logging struct-based and simplify configuration" (
cfd2312f0f)Not important: this prints the raw nanosecond count as the timestamp (e.g.
1758718542123456789). Maybe print seconds with a fractional part so it's readable at a glance (needs<iomanip>):re: https://github.com/bitcoin/bitcoin/pull/34374#discussion_r2731541954
@purpleKarrot I agree the singleton is worth getting rid of, but I think it can be removed later without any API changes, because this PR keeps
btck_LoggingConnectionhandles. I'm rebasing #30342 on top of this PR, and in that versionGetKernelLogger()goes away entirely: each logging connection becomes the logger that the kernel objects of its contexts log to, so there is no global logging state left in the kernel library. That is a bigger change than this PR, so I don't think the singleton here should block it.In commit "kernel: add missing log levels and categories" (
3a72f3040c)Minor, only affects intermediate commits: since
btck_LogCategory_LOCKis defined in every build but theget_bclog_flagcase for it only exists withDEBUG_LOCKCONTENTION, callingbtck_logging_enable_category(btck_LogCategory_LOCK)in a normal build hits theassert(false)untilget_bclog_flagis removed in the last commit. Could be avoided in this commit with:In commit "kernel: add KernelLogger" (
95e63e954a)Note for a followup: btcsignals could be used to simplify this code, see a85f463f69a048a72b154347ae4c362ed22579c3 (tag) . This gets rid of ~60 lines, and no kernel lock would be held while a callback or a
user_datadestroy callback runs, so the kind of deadlock w0xlt found can't happen. This also relates to your follow-up idea in https://github.com/bitcoin/bitcoin/pull/34374#discussion_r4034240501 of running callbacks without the lock.There are complications with this approach though so probably best to leave it alone here:
user_datawould be destroyed when that callback returns instead, like boost signals)StdMutex, since with DEBUG_LOCKORDER a detected lock order problem is logged while lock tracking state is locked.In commit "kernel: add KernelLogger" (
95e63e954a)Minor:
Log()takesm_mutexbefore checkingm_callbacks.empty(), so when no logging connection is registered, every Info-and-above entry in every kernel thread still serializes on the mutex, and at debug level statements are formatted only to be dropped. The earlierutil::log::Dispatcheravoided this with an atomicm_callback_count. An atomic count updated inRegisterCallback/UnregisterCallbackand checked inShouldLog()would cover both cases:In commit "kernel: make logging struct-based and simplify configuration" (
cfd2312f0f)Note: no change needed here, just a heads-up since it touches this function. I rebased #33847 on top of this PR, and it changes
btck_logging_set_min_levelto take the logging connection, with each connection filtering at its own level, plus abtck_context_options_set_loggerfunction to say which contexts a connection receives entries from. Happy to discuss it over there so it doesn't hold up this PR.In commit "kernel: make logging struct-based and simplify configuration" (
cfd2312f0f)Minor: after this PR the only function left that changes a logging setting is
btck_logging_set_min_level, so this could be more specific e.g. "The minimum level set with btck_logging_set_min_level is global and applies to all connections."In commit "kernel: expose btck_LogEntry" (
94cf10c4bf)Minor: since
timestamp_nsis the only time value in the kernel API in nanoseconds (themocktimefield below it,btck_set_mock_time, and thebtck_NotifyHeaderTiptimestamp are all seconds), and its actual precision depends on the platform's system clock, it might help to say both in the comment:In commit "kernel: make logging struct-based and simplify configuration" (
cfd2312f0f)Minor: this allows
WARNINGandERRORas minimum levels, so an application can hide warnings and errors. That seems fine (an application can also just not create a logging connection), but it might be good for the doc to steer away from doing this, e.g.: "Warning and Error entries report problems that usually need attention, so setting a minimum level above Info is not recommended for most applications."In commit "kernel: expose btck_LogEntry" (
94cf10c4bf)Timestamp()returns asys_timebutMockTime()returnsstd::chrono::seconds, which a duration, even though mock time is a point in time and 0 means no mock time is set. SinceLogEntryis new, it would seem more correct to returnstd::optional<std::chrono::sys_seconds>which is a time point not a duration, withstd::nulloptwhenmocktimeis unset.re: https://github.com/bitcoin/bitcoin/pull/34374#discussion_r2720709919
Tend to agree, and I posted a minimal diff in https://github.com/bitcoin/bitcoin/pull/34374#issuecomment-3813719678 that addresses this
Thanks for the reviews, @w0xlt and @ryanofsky! Force-pushed to address review comments from @ryanofsky:
KernelLoggerto reduce lock acquisition and unnecessary string formatting when no callbacks are registeredLogEntry::MockTime()type to astd::optional<std::chrono::sys_seconds>, and some related docstring/name updatesbtck_LogCategory_LOCKcategory in intermediate commits can no longer fail an assertion when compiled withoutDEBUG_LOCKCONTENTION.Going to leave this as-is. It seems (https://github.com/bitcoin/bitcoin/pull/36042) like we're reasonably close to being able to use
std::format, which would be the natural way to improve things in the C++ wrapper. Thebitcoin-chainstateandtest_kerneltimestamp output doesn't really matter much, I think.Fixed.
I explored using btcsignals earlier as per your earlier suggestion, but found it didn't completely fit the requirements yet. Could be interesting for a follow-up indeed, so I'll leave this unresolved for visibility, but agreed it shouldn't be done here.
I dropped that in this branch in my quest to simplify things as much as possible, but thinking about it again I agree that the cost is small enough for the benefit, so I've added it back in again. Thanks.
Going to leave this as-is. The globalness of
btck_logging_set_min_levelis already described in its docstring, so keeping thebtck_LoggingConnectiondocstring to generally describe its globalness seems simpler to me.I've only slightly reworded the docstring, there is nothing the user can/should do when their platform has a coarser time, so I'd rather keep the documentation concise there. I've used this opportunity to rename
mocktime->mocktime_sfor consistency and clarity, though.Going to leave this as-is. I think it's self-evident enough that warning and error logs are interesting to look at when looking at logs. Directionally, we also don't want to have log statements be part of the kernel interface, i.e. being things users must look at in order for their application to be safe or functioning correctly.
I wanted to not change the mocktime interface vs what we currently have, but you've changed my mind. This is the first time we're exposing this externally, and there is no point being consistent with an internal interface. Using
sys_secondsnow.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:
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.
Could we construct
UserDatabefore callingGetKernelLogger()?In my test, I request a connection from a global object’s constructor before
main(). This triggers the logger’s first creation. I deliberately made the memory allocation for that logger fail. Connection creation returned null, but the supplied cleanup callback was not called for the non-null user data.The issue is that
GetKernelLogger()is evaluated before theUserDataargument is constructed. If it throws, the data has not yet been placed in the wrapper that would clean it up.Could we move that construction onto the preceding line, inside the existing
tryblock?Is skipping the cleanup callback when
user_datais null intended?I passed null user data with a valid cleanup callback, then made the memory allocation for registering the callback fail. Creation returned null, but the cleanup callback was never called.
This happens because
unique_ptrdoes not invoke its deleter when its stored pointer is null. There is no user-data object to leak here, but the docs say the cleanup callback runs on error if provided.If skipping it is intended, could we make the extra condition explicit?
GetKernelLogger()just returns a reference to a static variable, so I think this is fine either way, but I'm happy to change it if I have to force-push. This feels like a nit to me so I'll consider it non-blocking unless I'm missing something?user_data_destroy_callbackis defined as "Nullable, function for freeing the user data.". Ifuser_datais null, there is nothing to free, so indeeduser_data_destroy_callbackshould not be called.A null
user_dataand non-nulluser_data_destroy_callbackis nonsensical and clearly a programmer error, so I think the correct approach is to assert this inbtck_logging_connection_createand update theuser_data_destroy_callbackdocstring there. I thought we were already doing this, but at least it seems it's no longer in the current branch so I'll fix that!Force-pushed to address review comments from @musaHaruna:
UserDatabefore callingGetKernelLogger()to ensureuser_datais always freed on erroruser_data_destroy_callbackdocstring to highlight that the destroy cb is not called whenuser_datais nullFixed, thanks!
I've changed my mind on this, and adopted your docstring updated, thanks! For
btck_ValidationInterfaceCallbacksandbtck_NotificationInterfaceCallbacks, we don't assert thatuser_data_destroyis null for a nulluser_data, and I don't have a strong enough view on having a different approach here to introduce the inconsistency. It still feels strange to have this happen, but perhaps there are valid reasons for it that I haven't thought of, so just documenting it now seems reasonable.Code review ACK
ad66992952. 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, theLOCKcategory no longer asserts in intermediate commits, anduser_datais now freed if getting the kernel logger throws.Thanks for considering the other suggestions, the reasons for leaving them out make sense to me.
In commit "kernel: add KernelLogger" (
bf1f4cb09d)Since this PR drops category filtering, I think it would be good to replace both
btck_LogCategory_ALLandbtck_LogCategory_UNKNOWNwith a singlebtck_LogCategory_NONE:ALLmade sense as a filter argument ("enable all categories"), but as the category of a delivered entry it is confusing. Log messages with no category are not from every category, they just don't have a category.UNKNOWNonly exists as the release-build fallback for an unmapped category, which is a kernel bug, not something kernel applications using our API should have to handle. We should handle it ourselves and not expose this externally by mapping these cases to NONE.Specific suggestion here would be to drop ALL and UNKNOWN and add NONE instead like:
The wrapper's
LogCategory::ALL/UNKNOWNand theirName()strings would change the same way.re: https://github.com/bitcoin/bitcoin/pull/34374#discussion_r4121137413
In commit "kernel: make logging struct-based and simplify configuration" (
ad66992952)Nit, only if you push again: with the "Not called if user_data is null" note on the parameter, the
@returnsentence could be dropped or made to match, e.g. "On error, user_data is freed as described above." Right now if read literally it would imply the callback can be called with a nulluser_dataon error.Base:
69142eacd1374925cc9e4ea736c21fcec16307d0Head:
eb086540b680cfed42ab7f9498c1ade459828808Design and approach
Confirm the cost of formatting all Debug and Trace categories (src/kernel/bitcoinkernel.cpp:972, head)
When Debug or Trace is enabled and a callback is registered, these hooks return true for every category. Logging macros then evaluate arguments and format messages before the callback can filter them. The base logger could suppress disabled categories earlier, and kernel-linked code has category-specific Debug logging, including LEVELDB and MEMPOOL. Is formatting every category acceptable for intended kernel consumers, or should a category prefilter remain? Consumer requirements or representative workload measurements would settle the tradeoff. A prefilter would add configuration state but preserve early suppression.
🟡 Minor
Messages ending in multiple newlines retain a trailing newline (src/kernel/bitcoinkernel.cpp:592, head)
For a message ending in two or more
\ncharacters, RemoveSuffixView removes only one, so the callback still receives a trailing newline despite the stated newline-free message behavior. Remove all trailing newlines or document that only one suffix newline is removed. No current kernel log producer ending in multiple newlines was identified, so production impact is unconfirmed.💡 Suggestion
Test teardown during an in-flight callback and pre-registration logging (src/test/kernel/test_kernel.cpp:717, head)
This test destroys connections only after callbacks return, so it does not verify that destruction waits for an in-flight callback. Add a synchronized test that blocks a callback, destroys its connection on another thread, and verifies the user-data destroy callback runs only after the blocked callback is released. Also test that a log entry emitted before registration is not replayed to a later connection.
Review coverage was incomplete. The archaeology review had incomplete evidence. The adversarial review had incomplete evidence. The adversarial_glm review had incomplete evidence. Verification was partial. Some candidate findings remain unresolved.
Full review report
The build passes
-fmacro-prefix-map=${PROJECT_SOURCE_DIR}/src=.(CMakeLists.txt), so source file names are expanded with a leading./. The node strips it when formatting source locations (RemovePrefixView(entry.source_loc.file_name(), "./")inBCLog::Logger::Format()), butKernelLogger::Logpasses the file name through unchanged, so kernel consumers get./validation.cppwhere node logs showvalidation.cpp.btck_LogEntry::file_nameas seen by a TRACE-level logging connection, before and after:The PR contains a subtle, undocumented behaviour change.
On master,
btck_logging_connection_createregistered the consumer's callback on the node's logger viaLogInstance().PushBackCallback(...). Each log line then went throughBCLog::Logger::Format(), which callsLogEscapeMessage(entry.message), before reaching the callback. Consumers got the escaping for free, because they received the same formatted line the node writes todebug.log.With this PR, the kernel has its own logger.
BCLog::Loggerno longer sits between the log statement and the kernel callback, andlogging.cppis no longer compiled into the kernel, soLogEscapeMessage()never runs.As I understand it, the point of the PR is to give consumers structured fields instead of a pre-formatted line, so escaping, like timestamp and prefix formatting, becomes the consumer's job. Could the docs say this explicitly?
nit:
nit:
Dead code (can be amended into
ad66992952).Force-pushed to address review comments from @ryanofsky and @w0xlt:
btck_LogCategory_ALLandbtck_LogCategory_UNKNOWNwith a singlebtck_LogCategory_NONEbtck_LogEntry::messageis not escapedbtck_LogCallbackandbtck_logging_connection_createBCLog::Logger::NumConnections()I went back and forth on this issue, and opted for
UNKNOWNas to make it easier for users to catch this bug since we cannot enforce it at compile-time.You've changed my mind, and I've now adopted your suggestion. It is still our responsibility to make sure unmapped categories don't happen, we have some ability to do so with
Assume, and polluting the public interface with something they should never see and should only minimally affect how they use the library is a bit excessive. Thanks!I don't think we need to match node behaviour here. It seems natural to use the path provided by the compiler, and whoever builds the library can control how source locations are returned through compiler flags (e.g.
-fmacro-prefix-map). The./prefix is also compiler-specific: with clang, the default build already returnsvalidation.cpp. So I think it makes sense to leave this as-is?Thanks, slightly updated the docstring to clarify it's unsanitized but I don't want to be overly verbose/prescriptive either.
Thanks, updated!
Thanks, updated!
Thanks, updated!
Good catch - removed it, thanks!
ACK
eb086540b6Code Review ACK eb08654
Thanks for incorporating my suggestions @stickies-v.
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.
Nice, ACK
eb086540b6There 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.
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.
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.
post-merge ACK
eb086540b6Done in #36584