mirror of
https://github.com/bitcoin/bitcoin
synced 2026-12-04 10:47:36 +00:00
logging: rewrite macros to enforce restrictions at compile-time, improve efficiency and usability #34778
No reviewers
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!34778
Loading…
Reference in a new issue
No description provided.
Delete branch "pr/relog"
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?
This PR is an internal cleanup for
util/log.hthat fixes several problems with the logging macros defined there.The main change is replacing the internal
detail_LogWithSrcLocmacro with aLOG_EMITmacro. It makes all the external logging macros (LogDebug,LogInfo, etc.) callLOG_EMIT, eliminating inconsistencies, improving efficiency, and producing clearer compiler errors when called incorrectly.Specific problems this PR fixes:
Current logging macros duplicate logic and have undocumented, untested differences. For example, some macros evaluate their arguments when logging is disabled and others do not. By constrast, the
LOG_EMITmacro implements logging logic in one place, preventing hidden inconsistencies.Current logging macros produce hard to decipher syntax errors when category arguments are specified but not allowed, or required but not provided. Now all logging macros produce clear
static_asserterrors indicating whether to add or remove category arguments.Current
LogInfo,LogWarning, andLogErrormacros generate log entries and callutil::log::Log(Entry)even when logging is disabled.LOG_EMITavoids this overhead, which is probably minor but could improve performance in some kernel applications and fuzzing.Current
detail_LogWithSrcLocmacro is dangerous to call because because it does not check for inconsistent or invalid arguments. For example, calling it always bypasses ratelimiting without a check to prevent this. (Previously there was a runtime check, but it was removed without justification in34332dba2f). NewLOG_EMITmacro is compile-time safe and all the same restrictions as other macros.Having multiple implementations of logging macros makes it difficult to add new logging features (see below), because it requires changing many macros and adding separate macro arguments for each feature. Having a single core
LOG_EMITmacro taking a single compile-timeoptionsargument makes it possible to add new features cleanly.Individual commits also implement other improvements: adding missing test coverage and removing misleading
Entry::should_ratelimitfield which is stored in buffered log messages after rate-limiting has been applied, and has no effect.Possible followups
This PR does not add any new logging features. It is purely an internal cleanup that fixes the problems listed above. However, it is worth noting that this PR could make it easier to add logging features in the future. For example:
New logging options could be added. Examples:
.stacktrace = trueto log the current stack trace,.exception = trueto log the current exception,.impossible = trueto indicate an impossible condition and halt fuzzing or request a bug report,.log_once = trueto log at most once from this source location,.log_every = 60mto log at most once per hour,.dedup = trueto drop duplicste messages, etc.External macros like
LogInfoandLogDebugcould accept these options. Example: f5ca95b1e610ebad7063143ddef98fc318251bc4Context information could be added to log messages, e.g., wallet names, chainstate names, or request IDs to distinguish logs from paralell requests. Example: #30343
Non-global logging streams could also be supported. For example, kernel functions could accept optional logger arguments instead of always writing to the global logger. Example: #30342
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.
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.
Concept NACK to reintroducing a generic
LogPrint. TheNO_RATE_LIMITcommit from #34038 has been available for review for three months now, and has had a concept ack for that long.That's interesting. #34038 is mostly a logging backend change, changing the RPC interface and command line options. It seems like the no-ratelimit change part of that PR might not be related to the other changes there? (I don't see the connection at least.)
To compare the two approaches, #34038 syntax looks like:
while syntax here is:
There is not much difference between the approaches externally, and they are compatible (this PR could easily support a
NO_RATE_LIMITflag if reviewers would prefer that.)This bigger goal of this PR is to replace current implementation of the logging macros which is messy and inconsistent with a clean implementation. All preprocessor functionality is implemented in a single macro called
LogPrint, getting rid of the branching code paths at different priority levels [1] [2] that have unexplained differences. The differences are all kept, they are just explicit rather than implicit, with better documentation and tests and stricter enforcement of restrictions.The
.ratelimit = trueoption is exposed as a side-effect of this refactoring, and the refactoring also allows other options to be implemented cleanly in the future. Examples could be.log_once=true.log_every=24h.log_every=60m.stack_trace=true.dedup = trueetc. I was also thinking of an.impossible = trueoption that could be used to document preconditions & provide better bug reports and output from fuzz & unit test failures. The point is that I think we should make it easy to add logging options and try to implement most options withconstexprcode instead of macros. And get rid of complication of different macros at different log levels having different implementations.Anyway I'd be happy to review #34038 and I think the runtime changes there look nice. The NO_RATE_LIMIT flag idea there could be nice. If reviewers like it maybe I could support it here and #34038 could be simpler and only implement the logging backend improvements without making a unrelated change (it would seem) to the logging macros?
not sure about using the internal/hidden macro here, after the changes. If someone wants to log at info level, it seems clearer to just call
LogInfo, instead of using some internal macro with a bunch of options.Also, supporting
.ratelimit = falsefor other levels doesn't really make sense, and certainly isn't needed by current code at all, so supporting it seems odd.edit: I see it is needed for one warning log as well. So I guess my main concern is that this will open the gates for the "wild west" that we were trying to fix: For example, this new macro may encourage to re-introduce helpers of the form:
[](auto level, auto msg) { LogPrint((.level=level),"%s", msg); }, which will then work incorrectly with regard to rate-limiting (silently dropping warnings/errors, when info logs overflow)re: https://github.com/bitcoin/bitcoin/pull/34778#discussion_r2912164572
When you say odd do you mean the code is doing something it should not do? Or not doing something it should do? For example, It would be easy to add a static assert to prevent ratelimiting being requested at certain levels if you feel that is important. Though I'm not sure why ratelimiting should not be available at different levels (I haven't looked into the rate limiting implementation).
Overall, the idea here is to accept options and pass them along the backend to implement. I imagine the bitcoinkernel backend probably won't support rate limiting at all for example (or at least it doesn't in #34374)
I've edited my comment to explain one case that will make code more brittle.
I mostly think this should remain internal/hidden, maybe
LogPrintInternalDetail(...). Otherwise, devs may think this is fine to use without thinking much about the implicit edges.re: https://github.com/bitcoin/bitcoin/pull/34778#discussion_r2912164572
Hmm, I'm confused why someone would do what you are suggesting, but if they did it should be safe and work correctly. The ratelimit default value should be the same as before.
The point of adding
LogPrintis to be a safe, single implementation of logging code that other macros can just forward to without their own bespoke logic and special cases.Please let me know if I am missing something here. Like I said I haven't actually looked at the ratelimiting implementation. This PR is just forwarding the option. If any unsafe option values are currently accepted, we should definitely prohibit them with a static assert, but I'm not seeing where that could be happening.
Well, you can go back in the git history to find this exact pattern. See
2210feb446.No, see
2210feb446, which fixed this. (You can refer to the commit messages for more details)re: https://github.com/bitcoin/bitcoin/pull/34778#discussion_r2912600904
Thanks for clarifying. For others who may be following, the pattern is shown specifically in
f273167661and94c51ae540and it is not allowed by this PR. This PR enforces the same restrictions as current code.E.g. if you try to revert
f273167661and callLogPrint((.level = ConvertIPCLogLevel(message.level)) , "%s\n", message.message);you will see an error because the level is not a compile time constant.(EDIT: I'd add that I don't see anything inherently wrong with the pattern used in those commits, and no reason it couldn't work well. The previous
LogPrintLevelimplemention just had a bug and was good candidate for removal for other reasons.)I don't think this is true. I am sure one can write a similar pattern deriving the level constexpr/consteval.
logging takes the source location, which is then used for other stuff (such as rate limiting or -logsourcelocations). Using the same source location for different logs is brittle in itself. Though, using it for different log levels is doubly brittle. I don't see the need to regress here
re: https://github.com/bitcoin/bitcoin/pull/34778#discussion_r2913106415
Can we slow down and try to work through an example here? I would like to understand the problem you are concerned about and either confirm that it is not an issue here, or make some fix to solve it.
As far as I can tell, you did a little pattern matching like "this new function looks similar to that previously removed function" and assuming "therefore it has the same bugs and limitations of the previous function." This is a reasonable assumption, but it happens not to be true in this case!
Sorry yes I should have clarified I only think the pattern is good for external code that does not include source locations. Internal logs should definitely have source locations! I don't think you will find any regressions on that front either implemented in this PR or enabled by it.
To the contrary, followup PR #30343 adds source locations to wallet code which is currently missing them.
Of course, this synthetic example is not found in the codebase as-is, but I don't see why it wouldn't compile with the changes in this pull
re: https://github.com/bitcoin/bitcoin/pull/34778#discussion_r2913611122
Thanks for the concrete example. I am assuming based on your earlier comments that problem with this example is that it hides source locations, and I agree hiding source locations would be bad. I guess I just disagree with the realism of the example. You seem to be saying is that this PR could make developers more tempted to write bad per-module logging interfaces and add calls like:
to the code, hiding source locations that would otherwise be available. Even though developers could implement literally the same bad interface today by calling the LogInfo/LogWarning/LogError macros with an
iforswitchstatement? And even though we already have an existingWalletLogPrintffunction today which has no problem hiding source locations with the current logging macros?I just don't see this PR by itself having any real impact on support for source locations. But if that is the concern and I did not misunderstand something, thanks for clarifying.
You give a real place yourself (
WalletLogPrintf), where a dev (or an LLM) could apply the example today (or use it as an excuse to introduce the pattern in another module) in any of the 300 open pulls. So I don't see why the example should not be real.Fair enough, but at least this won't apply rate-limiting across levels, when it shouldn't.
And to re-iterate an earlier point: Just as the logging was fixed to be consistent, so that one can call
git grep LogInfoto find all info logs, this will introduce a new alias to grep for. I am sure over time devs will then use (inside the same file), stuff like:I don't see the point in allowing all of this, if there is no reason for it. Why not just indicate in the name of the macro or function that this is only meant for internal use, like it was before this pull request?
Rebased 31612a7f5f0d197bdc4a9747ad9e7509bf693d7d -> 0c090593e8bdbdd3f65ea12aa1177ebc3d22d86a (
pr/relog.3->pr/relog.4, compare) due to conflict with #34865Rebased 0c090593e8bdbdd3f65ea12aa1177ebc3d22d86a ->
f0929e1b78(pr/relog.4->pr/relog.5, compare) due to conflict with #34806Rebased
f0929e1b78->4323986a35(pr/relog.5->pr/relog.6, compare) due to conflicts with #34729 and #36397, also updating the kernel log hooks for the macro rewrite now that #34374 is merged (previously done in #30342)This has not received review for half a year, has a N-A-C-K and maflcko's last comment wasn't replied to. Maybe this should be closed at this point?
🟠 Minor ·
-loglevelalwaysomits the category on Info, Warning, and Error linesWith
-loglevelalways=1, Info lines have no prefix and Warning/Error lines omitall:, contrary to the option’s help text.Location:
src/logging.cpp:359(head).🔵 Suggestion · Disabled Debug and Trace calls acquire the logger mutex
Every Debug or Trace call for a disabled category now locks
m_cs, adding hot-path contention that the base avoided; no availability impact is established.Location:
src/logging.cpp:625(head).🔵 Suggestion · Category masks and integers pass the logging category parameter
A masked category or integer now compiles, but can reach an assertion when logging is enabled; no current caller does this.
Location:
src/util/log.h:173(head).🔵 Suggestion · Argument-evaluation test never enables the category
The Debug and Trace assertions pass at both base and head, so they do not test whether the new logger-disabled gate skips argument evaluation.
Location:
src/test/logging_tests.cpp:592(head).🔵 Suggestion · Developer notes do not explain how to pass
ratelimit = falseThe documentation names a rate-limit option but gives no usable example, unlike the text it replaced.
Location:
doc/developer-notes.md:818(head).Reviewed:
4323986a35be· Full review report · Previous reportspermalink
Tested
f0929e1(also merged with master8406af1c).I ran into two issues:
-loglevelalwaysoutput changes. Withbitcoind -regtest -loglevelalways=1 -debug=net, the merge-base prints[all:info]on info lines, while this PR omits the prefix. In a unit test, warning and error lines are prefixed with[warning]and[error]instead of[all:warning]and[all:error].Is this change intentional? The help text still says "Always prepend a category and level", and the
98f3bd6commit message says there is no visible effect except in tests. If the change is intentional, could the help text be updated and the behavior mentioned in the release notes?LogDebugaccepts invalid flag types.LogDebugnow compiles when passed a plain integer or an OR-ed mask, whereas both failed to compile on the merge-base. For example,LogDebug(BCLog::NET | BCLog::HTTP, "x")aborts in a unit test whennetis enabled, atlogging.cpp:261, withAssertion 'it != LOG_CATEGORIES_BY_FLAG.end()' failed.LogDebug(1, "x")instead logs as[net].There are no such call sites in the current tree, so this mainly affects future code. Could
GetContexttakeBCLog::LogFlagsagain, so these invalid arguments are rejected at compile time?🐙 This pull request conflicts with the target branch and needs rebase.