zlog/ctx.go

53 lines
1.5 KiB
Go
Raw Normal View History

2022-03-20 19:19:42 +00:00
package zlog
2017-05-19 19:59:10 +00:00
2017-05-20 07:22:37 +00:00
import (
"context"
)
var disabledLogger *Logger
func init() {
2019-11-04 19:39:22 +00:00
SetGlobalLevel(TraceLevel)
l := Nop()
disabledLogger = &l
}
2017-05-19 19:59:10 +00:00
type ctxKey struct{}
// WithContext returns a copy of ctx with the receiver attached. The Logger
// attached to the provided Context (if any) will not be effected. If the
// receiver's log level is Disabled it will only be attached to the returned
// Context if the provided Context has a previously attached Logger. If the
// provided Context has no attached Logger, a Disabled Logger will not be
// attached.
2017-08-12 23:16:31 +00:00
//
// Note: to modify the existing Logger attached to a Context (instead of
// replacing it in a new Context), use UpdateContext with the following
2017-08-12 23:16:31 +00:00
// notation:
//
// ctx := r.Context()
2022-03-20 19:19:42 +00:00
// l := zlog.Ctx(ctx)
// l.UpdateContext(func(c Context) Context {
// return c.Str("bar", "baz")
// })
//
func (l Logger) WithContext(ctx context.Context) context.Context {
if _, ok := ctx.Value(ctxKey{}).(*Logger); !ok && 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, DefaultContextLogger is returned, unless DefaultContextLogger
// is nil, in which case a disabled logger is returned.
func Ctx(ctx context.Context) *Logger {
if l, ok := ctx.Value(ctxKey{}).(*Logger); ok {
return l
} else if l = DefaultContextLogger; l != nil {
return l
2017-05-20 07:22:37 +00:00
}
return disabledLogger
2017-05-19 19:59:10 +00:00
}