2018-04-30 18:42:17 +05:00
|
|
|
package zerolog
|
|
|
|
|
|
|
|
import (
|
|
|
|
"context"
|
|
|
|
)
|
|
|
|
|
|
|
|
var disabledLogger *Logger
|
|
|
|
|
|
|
|
func init() {
|
2019-03-07 07:56:50 +05:00
|
|
|
l := Nop()
|
2018-04-30 18:42:17 +05:00
|
|
|
disabledLogger = &l
|
|
|
|
}
|
|
|
|
|
|
|
|
type ctxKey struct{}
|
|
|
|
|
|
|
|
// WithContext returns a copy of ctx with l associated. If an instance of Logger
|
2019-03-07 07:56:50 +05:00
|
|
|
// is already in the context, the context is not updated.
|
2018-04-30 18:42:17 +05:00
|
|
|
//
|
|
|
|
// For instance, to add a field to an existing logger in the context, use this
|
|
|
|
// notation:
|
|
|
|
//
|
|
|
|
// ctx := r.Context()
|
|
|
|
// l := zerolog.Ctx(ctx)
|
2019-03-07 07:56:50 +05:00
|
|
|
// l.UpdateContext(func(c Context) Context {
|
|
|
|
// return c.Str("bar", "baz")
|
|
|
|
// })
|
|
|
|
func (l *Logger) WithContext(ctx context.Context) context.Context {
|
2018-04-30 18:42:17 +05:00
|
|
|
if lp, ok := ctx.Value(ctxKey{}).(*Logger); ok {
|
2019-03-07 07:56:50 +05:00
|
|
|
if lp == l {
|
|
|
|
// Do not store same logger.
|
|
|
|
return ctx
|
|
|
|
}
|
|
|
|
} else if l.level == Disabled {
|
2018-04-30 18:42:17 +05:00
|
|
|
// Do not store disabled logger.
|
|
|
|
return ctx
|
|
|
|
}
|
2019-03-07 07:56:50 +05:00
|
|
|
return context.WithValue(ctx, ctxKey{}, l)
|
2018-04-30 18:42:17 +05:00
|
|
|
}
|
|
|
|
|
|
|
|
// Ctx returns the Logger associated with the ctx. If no logger
|
|
|
|
// is associated, a disabled logger is returned.
|
|
|
|
func Ctx(ctx context.Context) *Logger {
|
|
|
|
if l, ok := ctx.Value(ctxKey{}).(*Logger); ok {
|
|
|
|
return l
|
|
|
|
}
|
|
|
|
return disabledLogger
|
|
|
|
}
|