[12.x] Log: Allow scoping log context to a callback #57971
Closed
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Description
This PR adds a
Log::withScopedContextmethod that allows one to add log context that is scoped to that callback. After the callback is executed the extra log context is removed again.Advantages
This mainly eases the use of #55181 (comment) and has similar advantages of using the callback with
Why
I frequently have code that executes separate tasks, e.g. custom jobs that do batches of work. There is a general context for the complete batch, plus a separate context for each unit of work. This means adding context before each unit of work and removing it afterwards.
I currently use
Log::withContext(...)combined withLog::withoutContext(...)afterwards, as described in the PR above. However, this can be a hassle for two reasons:This current solution addresses both problems.
Potential other solution
I could also see this working as an extension to
Log::withContext(...), by having the callback as a nullable second parameter. It would then function even more similar to howCache::lock()->get(...)works. I mainly chose the current solution for clarity, but have no real preference.Problems with the current solution
One unfortunate result of this solution is that it does not guarantee that the context at the end is the same as beforehand. This is primarily due to the
array_mergeusage inLog::withContext(...). This is fine for my use case, but it is something to take note of.