From e3027a573295768ea9478da3f0599083cf344a32 Mon Sep 17 00:00:00 2001 From: Tim Peoples Date: Sat, 22 Oct 2022 10:29:38 -0700 Subject: [PATCH] Fix docs and behavior of WithContext (#499) --- ctx.go | 19 ++++++++++--------- 1 file changed, 10 insertions(+), 9 deletions(-) diff --git a/ctx.go b/ctx.go index 44d3f4b..60432d1 100644 --- a/ctx.go +++ b/ctx.go @@ -14,10 +14,15 @@ func init() { type ctxKey struct{} -// WithContext returns a copy of ctx with l associated. If an instance of Logger -// is already in the context, the context is not updated. +// WithContext returns a copy of ctx with the receiver attached. The Logger +// attached to the provided Context (if any) will not be effected. If the +// receiver's log level is Disabled it will only be attached to the returned +// Context if the provided Context has a previously attached Logger. If the +// provided Context has no attached Logger, a Disabled Logger will not be +// attached. // -// For instance, to add a field to an existing logger in the context, use this +// Note: to modify the existing Logger attached to a Context (instead of +// replacing it in a new Context), use UpdateContext with the following // notation: // // ctx := r.Context() @@ -25,13 +30,9 @@ type ctxKey struct{} // l.UpdateContext(func(c Context) Context { // return c.Str("bar", "baz") // }) +// func (l Logger) WithContext(ctx context.Context) context.Context { - if lp, ok := ctx.Value(ctxKey{}).(*Logger); ok { - if lp == &l { - // Do not store same logger. - return ctx - } - } else if l.level == Disabled { + if _, ok := ctx.Value(ctxKey{}).(*Logger); !ok && l.level == Disabled { // Do not store disabled logger. return ctx }