1
0
mirror of https://github.com/woodpecker-ci/woodpecker.git synced 2024-12-18 08:26:45 +02:00
woodpecker/vendor/github.com/rs/zerolog/ctx.go

47 lines
1.1 KiB
Go
Raw Normal View History

2017-08-03 21:36:22 +02:00
package zerolog
import (
"context"
"io/ioutil"
)
2017-09-12 20:25:55 +02:00
var disabledLogger *Logger
func init() {
l := New(ioutil.Discard).Level(Disabled)
disabledLogger = &l
}
2017-08-03 21:36:22 +02:00
type ctxKey struct{}
2017-09-12 20:25:55 +02:00
// WithContext returns a copy of ctx with l associated. If an instance of Logger
// is already in the context, the pointer to this logger is updated with l.
//
// For instance, to add a field to an existing logger in the context, use this
// notation:
//
// ctx := r.Context()
// l := zerolog.Ctx(ctx)
// ctx = l.With().Str("foo", "bar").WithContext(ctx)
2017-08-03 21:36:22 +02:00
func (l Logger) WithContext(ctx context.Context) context.Context {
if lp, ok := ctx.Value(ctxKey{}).(*Logger); ok {
// Update existing pointer.
*lp = l
return ctx
}
2017-09-12 20:25:55 +02:00
if l.level == Disabled {
// Do not store disabled logger.
return ctx
}
2017-08-03 21:36:22 +02:00
return context.WithValue(ctx, ctxKey{}, &l)
}
// Ctx returns the Logger associated with the ctx. If no logger
// is associated, a disabled logger is returned.
2017-09-12 20:25:55 +02:00
func Ctx(ctx context.Context) *Logger {
2017-08-03 21:36:22 +02:00
if l, ok := ctx.Value(ctxKey{}).(*Logger); ok {
2017-09-12 20:25:55 +02:00
return l
2017-08-03 21:36:22 +02:00
}
return disabledLogger
}