Skip to content

Commit

Permalink
Fix docs and behavior of WithContext (#499)
Browse files Browse the repository at this point in the history
  • Loading branch information
tep authored Oct 22, 2022
1 parent a9a8199 commit e3027a5
Showing 1 changed file with 10 additions and 9 deletions.
19 changes: 10 additions & 9 deletions ctx.go
Original file line number Diff line number Diff line change
Expand Up @@ -14,24 +14,25 @@ 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()
// l := zerolog.Ctx(ctx)
// 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
}
Expand Down

0 comments on commit e3027a5

Please sign in to comment.