Allow user configuration of which logger to return from Ctx() (#343)
If a user is trying to fetch a logger from their context, they probably want to log something. In order to allow returning a useable logger from Ctx() without breaking backwards compatibilty with the previous behavior, we make it configurable.
This commit is contained in:
parent
fad20d83d3
commit
d92a906fca
5
ctx.go
5
ctx.go
|
@ -39,10 +39,13 @@ func (l *Logger) WithContext(ctx context.Context) context.Context {
|
||||||
}
|
}
|
||||||
|
|
||||||
// Ctx returns the Logger associated with the ctx. If no logger
|
// Ctx returns the Logger associated with the ctx. If no logger
|
||||||
// is associated, a disabled logger is returned.
|
// is associated, DefaultContextLogger is returned, unless DefaultContextLogger
|
||||||
|
// is nil, in which case a disabled logger is returned.
|
||||||
func Ctx(ctx context.Context) *Logger {
|
func Ctx(ctx context.Context) *Logger {
|
||||||
if l, ok := ctx.Value(ctxKey{}).(*Logger); ok {
|
if l, ok := ctx.Value(ctxKey{}).(*Logger); ok {
|
||||||
return l
|
return l
|
||||||
|
} else if l = DefaultContextLogger; l != nil {
|
||||||
|
return l
|
||||||
}
|
}
|
||||||
return disabledLogger
|
return disabledLogger
|
||||||
}
|
}
|
||||||
|
|
|
@ -27,6 +27,13 @@ func TestCtx(t *testing.T) {
|
||||||
if log2 != disabledLogger {
|
if log2 != disabledLogger {
|
||||||
t.Error("Ctx did not return the expected logger")
|
t.Error("Ctx did not return the expected logger")
|
||||||
}
|
}
|
||||||
|
|
||||||
|
DefaultContextLogger = &log
|
||||||
|
t.Cleanup(func() { DefaultContextLogger = nil })
|
||||||
|
log2 = Ctx(context.Background())
|
||||||
|
if log2 != &log {
|
||||||
|
t.Error("Ctx did not return the expected logger")
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
func TestCtxDisabled(t *testing.T) {
|
func TestCtxDisabled(t *testing.T) {
|
||||||
|
|
|
@ -100,6 +100,10 @@ var (
|
||||||
// output. If not set, an error is printed on the stderr. This handler must
|
// output. If not set, an error is printed on the stderr. This handler must
|
||||||
// be thread safe and non-blocking.
|
// be thread safe and non-blocking.
|
||||||
ErrorHandler func(err error)
|
ErrorHandler func(err error)
|
||||||
|
|
||||||
|
// DefaultContextLogger is returned from Ctx() if there is no logger associated
|
||||||
|
// with the context.
|
||||||
|
DefaultContextLogger *Logger
|
||||||
)
|
)
|
||||||
|
|
||||||
var (
|
var (
|
||||||
|
|
Loading…
Reference in New Issue