Skip to content

Commit d92a906

Browse files
authored
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.
1 parent fad20d8 commit d92a906

File tree

3 files changed

+15
-1
lines changed

3 files changed

+15
-1
lines changed

ctx.go

+4-1
Original file line numberDiff line numberDiff line change
@@ -39,10 +39,13 @@ func (l *Logger) WithContext(ctx context.Context) context.Context {
3939
}
4040

4141
// Ctx returns the Logger associated with the ctx. If no logger
42-
// is associated, a disabled logger is returned.
42+
// is associated, DefaultContextLogger is returned, unless DefaultContextLogger
43+
// is nil, in which case a disabled logger is returned.
4344
func Ctx(ctx context.Context) *Logger {
4445
if l, ok := ctx.Value(ctxKey{}).(*Logger); ok {
4546
return l
47+
} else if l = DefaultContextLogger; l != nil {
48+
return l
4649
}
4750
return disabledLogger
4851
}

ctx_test.go

+7
Original file line numberDiff line numberDiff line change
@@ -27,6 +27,13 @@ func TestCtx(t *testing.T) {
2727
if log2 != disabledLogger {
2828
t.Error("Ctx did not return the expected logger")
2929
}
30+
31+
DefaultContextLogger = &log
32+
t.Cleanup(func() { DefaultContextLogger = nil })
33+
log2 = Ctx(context.Background())
34+
if log2 != &log {
35+
t.Error("Ctx did not return the expected logger")
36+
}
3037
}
3138

3239
func TestCtxDisabled(t *testing.T) {

globals.go

+4
Original file line numberDiff line numberDiff line change
@@ -100,6 +100,10 @@ var (
100100
// output. If not set, an error is printed on the stderr. This handler must
101101
// be thread safe and non-blocking.
102102
ErrorHandler func(err error)
103+
104+
// DefaultContextLogger is returned from Ctx() if there is no logger associated
105+
// with the context.
106+
DefaultContextLogger *Logger
103107
)
104108

105109
var (

0 commit comments

Comments
 (0)