2017-05-19 19:59:10 +00:00
|
|
|
package zerolog
|
|
|
|
|
2017-05-20 07:22:37 +00:00
|
|
|
import (
|
|
|
|
"context"
|
|
|
|
)
|
|
|
|
|
2017-08-30 05:53:32 +00:00
|
|
|
var disabledLogger *Logger
|
|
|
|
|
|
|
|
func init() {
|
2019-11-04 19:39:22 +00:00
|
|
|
SetGlobalLevel(TraceLevel)
|
2018-07-03 01:23:53 +00:00
|
|
|
l := Nop()
|
2017-08-30 05:53:32 +00:00
|
|
|
disabledLogger = &l
|
|
|
|
}
|
2017-05-19 19:59:10 +00:00
|
|
|
|
|
|
|
type ctxKey struct{}
|
|
|
|
|
2017-08-12 23:16:31 +00:00
|
|
|
// WithContext returns a copy of ctx with l associated. If an instance of Logger
|
2018-07-03 01:23:53 +00:00
|
|
|
// is already in the context, the context is not updated.
|
2017-08-12 23:16:31 +00:00
|
|
|
//
|
|
|
|
// For instance, to add a field to an existing logger in the context, use this
|
|
|
|
// notation:
|
|
|
|
//
|
|
|
|
// ctx := r.Context()
|
|
|
|
// l := zerolog.Ctx(ctx)
|
2018-07-03 01:23:53 +00:00
|
|
|
// l.UpdateContext(func(c Context) Context {
|
|
|
|
// return c.Str("bar", "baz")
|
|
|
|
// })
|
|
|
|
func (l *Logger) WithContext(ctx context.Context) context.Context {
|
2017-05-20 08:48:00 +00:00
|
|
|
if lp, ok := ctx.Value(ctxKey{}).(*Logger); ok {
|
2018-07-03 01:23:53 +00:00
|
|
|
if lp == l {
|
|
|
|
// Do not store same logger.
|
|
|
|
return ctx
|
|
|
|
}
|
|
|
|
} else if l.level == Disabled {
|
2017-08-30 05:53:32 +00:00
|
|
|
// Do not store disabled logger.
|
|
|
|
return ctx
|
|
|
|
}
|
2018-07-03 01:23:53 +00:00
|
|
|
return context.WithValue(ctx, ctxKey{}, l)
|
2017-05-19 19:59:10 +00:00
|
|
|
}
|
|
|
|
|
2017-05-20 07:22:37 +00:00
|
|
|
// Ctx returns the Logger associated with the ctx. If no logger
|
|
|
|
// is associated, a disabled logger is returned.
|
2017-08-30 05:53:32 +00:00
|
|
|
func Ctx(ctx context.Context) *Logger {
|
2017-05-20 08:48:00 +00:00
|
|
|
if l, ok := ctx.Value(ctxKey{}).(*Logger); ok {
|
2017-08-30 05:53:32 +00:00
|
|
|
return l
|
2017-05-20 07:22:37 +00:00
|
|
|
}
|
|
|
|
return disabledLogger
|
2017-05-19 19:59:10 +00:00
|
|
|
}
|