Skip to content

Commit

Permalink
Allow user configuration of which logger to return from Ctx() (#343)
Browse files Browse the repository at this point in the history
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.
  • Loading branch information
sean-rn authored Aug 12, 2021
1 parent fad20d8 commit d92a906
Show file tree
Hide file tree
Showing 3 changed files with 15 additions and 1 deletion.
5 changes: 4 additions & 1 deletion ctx.go
Original file line number Diff line number Diff line change
Expand Up @@ -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
}
7 changes: 7 additions & 0 deletions ctx_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -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) {
Expand Down
4 changes: 4 additions & 0 deletions globals.go
Original file line number Diff line number Diff line change
Expand Up @@ -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 (
Expand Down

0 comments on commit d92a906

Please sign in to comment.