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"
|
|
|
|
)
|
|
|
|
|
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{}
|
|
|
|
|
2022-10-22 17:29:38 +00:00
|
|
|
// 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
|
|
|
//
|
2022-10-22 17:29:38 +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)
|
2018-07-03 01:23:53 +00:00
|
|
|
// l.UpdateContext(func(c Context) Context {
|
|
|
|
// return c.Str("bar", "baz")
|
|
|
|
// })
|
2022-10-22 17:29:38 +00:00
|
|
|
//
|
2022-02-24 00:17:11 +00:00
|
|
|
func (l Logger) WithContext(ctx context.Context) context.Context {
|
2022-10-22 17:29:38 +00:00
|
|
|
if _, ok := ctx.Value(ctxKey{}).(*Logger); !ok && l.level == Disabled {
|
2017-08-30 05:53:32 +00:00
|
|
|
// Do not store disabled logger.
|
|
|
|
return ctx
|
|
|
|
}
|
2022-02-24 00:17:11 +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
|
2021-08-12 00:18:16 +00:00
|
|
|
// is associated, DefaultContextLogger is returned, unless DefaultContextLogger
|
|
|
|
// is nil, in which case 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
|
2021-08-12 00:18:16 +00:00
|
|
|
} 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
|
|
|
}
|