Skip to content

Commit

Permalink
Preserve context in With() calls (#17)
Browse files Browse the repository at this point in the history
Currently `With()` will reset context back to `context.Background()`,
causing the `wrap/wrapf` calls to lose the original context.

This affects the `clog/gcp` handler who relies on a value keyed with
`"trace"` being set on the context
([see](https://github.com/chainguard-dev/clog/blob/main/gcp/trace.go#L110-L116))
(we should use a typed value though, but that's in a different PR).

---------

Signed-off-by: Nghia Tran <tcnghia@gmail.com>
  • Loading branch information
tcnghia authored Jun 19, 2024
1 parent cb30939 commit f300b26
Show file tree
Hide file tree
Showing 2 changed files with 15 additions and 2 deletions.
4 changes: 2 additions & 2 deletions logger.go
Original file line number Diff line number Diff line change
Expand Up @@ -53,12 +53,12 @@ func With(args ...any) *Logger {

// With calls [Logger.With] on the logger.
func (l *Logger) With(args ...any) *Logger {
return NewLogger(l.Logger.With(args...))
return NewLoggerWithContext(l.context(), l.Logger.With(args...))
}

// WithGroup calls [Logger.WithGroup] on the default logger.
func (l *Logger) WithGroup(name string) *Logger {
return NewLogger(l.Logger.WithGroup(name))
return NewLoggerWithContext(l.context(), l.Logger.WithGroup(name))
}

func (l *Logger) context() context.Context {
Expand Down
13 changes: 13 additions & 0 deletions logger_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -113,3 +113,16 @@ func TestLoggerPC(t *testing.T) {
t.Errorf("want %v, got %v", want, got)
}
}

func TestWith(t *testing.T) {
ctx := context.WithValue(context.Background(), "test", "test")
log := NewLoggerWithContext(ctx, nil)
withed := log.With("a", "b")
if want := withed.ctx; want != ctx {
t.Errorf("want %v, got %v", want, ctx)
}
withed = log.WithGroup("a")
if want := withed.ctx; want != ctx {
t.Errorf("want %v, got %v", want, ctx)
}
}

0 comments on commit f300b26

Please sign in to comment.