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