Skip to content

feat(logging): add WithHandlerMiddleware option to NewHandler - #304

Open
reyortiz3 wants to merge 1 commit into
mainfrom
feat/logging-handler-middleware
Open

reyortiz3 wants to merge 1 commit into
mainfrom
feat/logging-handler-middleware

Conversation

@reyortiz3

Copy link
Copy Markdown
Contributor

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:

handler := logging.NewHandler(logging.WithFormat(logging.FormatText), logging.WithLevel(level))
handler = myTraceContextHandler(handler)

This adds a WithHandlerMiddleware option so that wrap can be expressed declaratively in the options list instead, without logging taking a dependency on OTel or anything else — it only knows about func(slog.Handler) slog.Handler.

Changes

  • WithHandlerMiddleware(fn func(slog.Handler) slog.Handler) Option — appends fn to an ordered list; NewHandler folds 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 to NewHandler.

Verification

  • task lint: 0 issues
  • task test (full module, -race): all packages pass
  • task license-check: passes
  • New tests: TestNewHandler_WithHandlerMiddleware (wraps the handler, no-op with no middleware given, multiple middlewares apply in the documented order)

Scope

Only logging/logging.go and logging/logging_test.go.

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

1 participant