blob: 2b7a682399e268ce68a87fca18dbdb77109484fc [file] [log] [blame]
khenaidooac637102019-01-14 15:44:34 -05001package zerolog
2
3import (
4 "context"
5)
6
7var disabledLogger *Logger
8
9func init() {
10 l := Nop()
11 disabledLogger = &l
12}
13
14type ctxKey struct{}
15
16// WithContext returns a copy of ctx with l associated. If an instance of Logger
17// is already in the context, the context is not updated.
18//
19// For instance, to add a field to an existing logger in the context, use this
20// notation:
21//
22// ctx := r.Context()
23// l := zerolog.Ctx(ctx)
24// l.UpdateContext(func(c Context) Context {
25// return c.Str("bar", "baz")
26// })
27func (l *Logger) WithContext(ctx context.Context) context.Context {
28 if lp, ok := ctx.Value(ctxKey{}).(*Logger); ok {
29 if lp == l {
30 // Do not store same logger.
31 return ctx
32 }
33 } else if l.level == Disabled {
34 // Do not store disabled logger.
35 return ctx
36 }
37 return context.WithValue(ctx, ctxKey{}, l)
38}
39
40// Ctx returns the Logger associated with the ctx. If no logger
41// is associated, a disabled logger is returned.
42func Ctx(ctx context.Context) *Logger {
43 if l, ok := ctx.Value(ctxKey{}).(*Logger); ok {
44 return l
45 }
46 return disabledLogger
47}