Evstigneev Denis
38c5fe8b5a
All checks were successful
test / test (push) Successful in 42s
## Pull Request template Please, go through these steps before clicking submit on this PR. 1. Give a descriptive title to your PR. 2. Provide a description of your changes. 3. Make sure you have some relevant tests. 4. Put `closes #XXXX` in your comment to auto-close the issue that your PR fixes (if applicable). **PLEASE REMOVE THIS TEMPLATE BEFORE SUBMITTING** Reviewed-on: #369 Co-authored-by: Evstigneev Denis <danteevstigneev@yandex.ru> Co-committed-by: Evstigneev Denis <danteevstigneev@yandex.ru>
44 lines
1014 B
Go
44 lines
1014 B
Go
package logger
|
|
|
|
import "context"
|
|
|
|
type loggerKey struct{}
|
|
|
|
// MustContext returns logger from passed context or DefaultLogger if empty
|
|
func MustContext(ctx context.Context) Logger {
|
|
if ctx == nil {
|
|
return DefaultLogger.Clone()
|
|
}
|
|
if l, ok := ctx.Value(loggerKey{}).(Logger); ok && l != nil {
|
|
return l
|
|
}
|
|
return DefaultLogger.Clone()
|
|
}
|
|
|
|
// FromContext returns logger from passed context
|
|
func FromContext(ctx context.Context) (Logger, bool) {
|
|
if ctx == nil {
|
|
return nil, false
|
|
}
|
|
l, ok := ctx.Value(loggerKey{}).(Logger)
|
|
return l, ok
|
|
}
|
|
|
|
// NewContext stores logger into passed context
|
|
func NewContext(ctx context.Context, l Logger) context.Context {
|
|
if ctx == nil {
|
|
ctx = context.Background()
|
|
}
|
|
return context.WithValue(ctx, loggerKey{}, l)
|
|
}
|
|
|
|
// 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)
|
|
}
|
|
}
|