Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

ctx: Modify WithContext to use a non-pointer receiver #409

Merged
merged 1 commit into from Feb 24, 2022
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
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 {
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

So this change makes no sense. Value receiver methods get a new copy of l every time they are called. So here you are taking an address of this temporary copied value and comparing it with context pointer. This will always be false. This has been fixed by removing this check in #499.

// 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")
}
}