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.mdeliminate universal boilerplate — this is exactly the shape of helper that belongs in the package.

Design notes

  • Signature ...any mirrors slog.Logger.With so callers can pass either typed slog.Attr values 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 AppendFields matches 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 fields to align with the package's vocabulary (Fields, AppendFields, the typed log.HTTPMethod/log.CorrelationID field helpers) rather than slog's lower-level attrs term.
  • 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 AppendFields calls 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

Merge request reports

Loading
Loading