Conversation
Lets callers wrap the handler NewHandler builds with a func(slog.Handler) slog.Handler before it's returned, so a cross-cutting concern (trace-context stamping, redaction, sampling, ...) can be injected declaratively via the options list instead of a separate reassignment statement after the call, with no OTel or other dependency added to this package. Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
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.
Motivation
Consumers that need to wrap
logging.NewHandler's returned handler with a cross-cutting concern (trace-context stamping, redaction, sampling, ...) currently do it as a separate reassignment after the call:This adds a
WithHandlerMiddlewareoption so that wrap can be expressed declaratively in the options list instead, withoutloggingtaking a dependency on OTel or anything else — it only knows aboutfunc(slog.Handler) slog.Handler.Changes
WithHandlerMiddleware(fn func(slog.Handler) slog.Handler) Option— appendsfnto an ordered list;NewHandlerfolds them over the base handler before returning. Multiple middlewares apply in call order, so the last one wraps outermost and sees each record first (documented and tested).New(opts...)picks this up for free since it just forwards toNewHandler.Verification
task lint: 0 issuestask test(full module,-race): all packages passtask license-check: passesTestNewHandler_WithHandlerMiddleware(wraps the handler, no-op with no middleware given, multiple middlewares apply in the documented order)Scope
Only
logging/logging.goandlogging/logging_test.go.