2020-02-10 00:26:46 +03:00
|
|
|
package logger
|
|
|
|
|
|
|
|
import "context"
|
|
|
|
|
|
|
|
type loggerKey struct{}
|
|
|
|
|
2024-05-09 16:41:22 +03:00
|
|
|
// MustContext returns logger from passed context or DefaultLogger if empty
|
|
|
|
func MustContext(ctx context.Context) Logger {
|
|
|
|
if ctx == nil {
|
|
|
|
return DefaultLogger
|
|
|
|
}
|
|
|
|
if l, ok := ctx.Value(loggerKey{}).(Logger); ok && l != nil {
|
|
|
|
return l
|
|
|
|
}
|
|
|
|
return DefaultLogger
|
|
|
|
}
|
|
|
|
|
2020-11-02 13:25:29 +03:00
|
|
|
// FromContext returns logger from passed context
|
2020-02-10 00:26:46 +03:00
|
|
|
func FromContext(ctx context.Context) (Logger, bool) {
|
2020-12-17 22:52:00 +03:00
|
|
|
if ctx == nil {
|
|
|
|
return nil, false
|
|
|
|
}
|
2020-02-10 00:26:46 +03:00
|
|
|
l, ok := ctx.Value(loggerKey{}).(Logger)
|
|
|
|
return l, ok
|
|
|
|
}
|
|
|
|
|
2020-11-02 13:25:29 +03:00
|
|
|
// NewContext stores logger into passed context
|
2020-02-10 00:26:46 +03:00
|
|
|
func NewContext(ctx context.Context, l Logger) context.Context {
|
2020-12-17 22:52:00 +03:00
|
|
|
if ctx == nil {
|
|
|
|
ctx = context.Background()
|
|
|
|
}
|
2020-02-10 00:26:46 +03:00
|
|
|
return context.WithValue(ctx, loggerKey{}, l)
|
|
|
|
}
|
2020-12-07 16:10:20 +03:00
|
|
|
|
|
|
|
// SetOption returns a function to setup a context with given value
|
|
|
|
func SetOption(k, v interface{}) Option {
|
|
|
|
return func(o *Options) {
|
|
|
|
if o.Context == nil {
|
|
|
|
o.Context = context.Background()
|
|
|
|
}
|
|
|
|
o.Context = context.WithValue(o.Context, k, v)
|
|
|
|
}
|
|
|
|
}
|