zlog/ctx.go

48 lines
1.1 KiB
Go
Raw Normal View History

2017-05-19 19:59:10 +00:00
package zerolog
2017-05-20 07:22:37 +00:00
import (
"context"
)
var disabledLogger *Logger
func init() {
l := Nop()
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
// 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)
// 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 {
// Do not store disabled logger.
return ctx
}
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.
func Ctx(ctx context.Context) *Logger {
if l, ok := ctx.Value(ctxKey{}).(*Logger); ok {
return l
2017-05-20 07:22:37 +00:00
}
return disabledLogger
2017-05-19 19:59:10 +00:00
}