Loading
feat(v2/log): add AppendFields helper for context logger enrichment
What
Adds log.AppendFields(ctx, fields...) to v2/log — a shorthand for the
existing pattern WithLogger(ctx, FromContext(ctx).With(fields...)).
func AppendFields(ctx context.Context, fields ...any) context.Context {
return WithLogger(ctx, FromContext(ctx).With(fields...))
}Call sites change from:
ctx = log.WithLogger(ctx, log.FromContext(ctx).With(
log.HTTPMethod(request.Method),
log.HTTPURL(request.URL.String()),
))to:
ctx = log.AppendFields(ctx,
log.HTTPMethod(request.Method),
log.HTTPURL(request.URL.String()),
)Why
Surfaced as review feedback during the gitlab-shell migration to v2/log: the three-call wrapper was being repeated 20+ times to layer request-scoped fields onto the context logger as a request flowed through the call chain. Per the repo's own design guideline in AGENTS.md — eliminate universal boilerplate — this is exactly the shape of helper that belongs in the package.
Design notes
- Signature
...anymirrorsslog.Logger.Withso callers can pass either typedslog.Attrvalues from the existing field constructors (log.HTTPMethod,log.CorrelationID, …) or loose key-value pairs. Drop-in replacement for the pattern it supersedes — no caller changes required when migrating. - Naming
AppendFieldsmatches how the package's godoc already refers to its typed helpers (e.g. "returns an slog.Attr for the method field"). "Append" makes the accumulating semantics explicit: each call layers on top of the previous logger. - Parameter named
fieldsto align with the package's vocabulary (Fields,AppendFields, the typedlog.HTTPMethod/log.CorrelationIDfield helpers) rather than slog's lower-levelattrsterm. - Missing-logger behaviour is inherited from
FromContext, which falls back to a default logger and emits a debug line. No special handling needed at this layer. - Purely additive — no changes to existing API.
How to verify
cd v2 && go test ./log/...Coverage added in TestAppendFields:
- appends attributes that show up on subsequent log records
- multiple
AppendFieldscalls accumulate - works with the typed field helpers (the realistic call site)
- falls back to a default logger when no logger is in context
An ExampleAppendFields is also added to example_test.go showing the
typical request-flow usage.
Edited by Elliot Forbes