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:
Sean 2021-08-11 20:18:16 -04:00 committed by GitHub
parent fad20d83d3
commit d92a906fca
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
3 changed files with 15 additions and 1 deletions

5
ctx.go
View File

@ -39,10 +39,13 @@ func (l *Logger) WithContext(ctx context.Context) context.Context {
}
// 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 {
if l, ok := ctx.Value(ctxKey{}).(*Logger); ok {
return l
} else if l = DefaultContextLogger; l != nil {
return l
}
return disabledLogger
}

View File

@ -27,6 +27,13 @@ func TestCtx(t *testing.T) {
if log2 != disabledLogger {
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) {

View File

@ -100,6 +100,10 @@ var (
// output. If not set, an error is printed on the stderr. This handler must
// be thread safe and non-blocking.
ErrorHandler func(err error)
// DefaultContextLogger is returned from Ctx() if there is no logger associated
// with the context.
DefaultContextLogger *Logger
)
var (