Skip to content

Commit

Permalink
ctx: Modify WithContext to use a non-pointer receiver (rs#409)
Browse files Browse the repository at this point in the history
  • Loading branch information
nickcorin authored and pablitoc committed Apr 7, 2023
1 parent e220bba commit e0e2d18
Show file tree
Hide file tree
Showing 2 changed files with 7 additions and 7 deletions.
6 changes: 3 additions & 3 deletions ctx.go
Expand Up @@ -25,17 +25,17 @@ type ctxKey struct{}
// l.UpdateContext(func(c Context) Context {
// return c.Str("bar", "baz")
// })
func (l *Logger) WithContext(ctx context.Context) context.Context {
func (l Logger) WithContext(ctx context.Context) context.Context {
if lp, ok := ctx.Value(ctxKey{}).(*Logger); ok {
if lp == l {
if lp == &l {
// Do not store same logger.
return ctx
}
} else if l.level == Disabled {
// Do not store disabled logger.
return ctx
}
return context.WithValue(ctx, ctxKey{}, l)
return context.WithValue(ctx, ctxKey{}, &l)
}

// Ctx returns the Logger associated with the ctx. If no logger
Expand Down
8 changes: 4 additions & 4 deletions ctx_test.go
Expand Up @@ -45,26 +45,26 @@ func TestCtxDisabled(t *testing.T) {

l := New(ioutil.Discard).With().Str("foo", "bar").Logger()
ctx = l.WithContext(ctx)
if Ctx(ctx) != &l {
if !reflect.DeepEqual(Ctx(ctx), &l) {
t.Error("WithContext did not store logger")
}

l.UpdateContext(func(c Context) Context {
return c.Str("bar", "baz")
})
ctx = l.WithContext(ctx)
if Ctx(ctx) != &l {
if !reflect.DeepEqual(Ctx(ctx), &l) {
t.Error("WithContext did not store updated logger")
}

l = l.Level(DebugLevel)
ctx = l.WithContext(ctx)
if Ctx(ctx) != &l {
if !reflect.DeepEqual(Ctx(ctx), &l) {
t.Error("WithContext did not store copied logger")
}

ctx = dl.WithContext(ctx)
if Ctx(ctx) != &dl {
if !reflect.DeepEqual(Ctx(ctx), &dl) {
t.Error("WithContext did not override logger with a disabled logger")
}
}

0 comments on commit e0e2d18

Please sign in to comment.