From d92a906fcad9c1b4166e1a2e3d7321e19cdeece9 Mon Sep 17 00:00:00 2001 From: Sean <77011910+sean-rn@users.noreply.github.com> Date: Wed, 11 Aug 2021 20:18:16 -0400 Subject: [PATCH] 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. --- ctx.go | 5 ++++- ctx_test.go | 7 +++++++ globals.go | 4 ++++ 3 files changed, 15 insertions(+), 1 deletion(-) diff --git a/ctx.go b/ctx.go index ce18a32c..966d17ed 100644 --- a/ctx.go +++ b/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 -// 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 } diff --git a/ctx_test.go b/ctx_test.go index 646cd0fb..23558930 100644 --- a/ctx_test.go +++ b/ctx_test.go @@ -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) { diff --git a/globals.go b/globals.go index 98c67edb..e561d8f3 100644 --- a/globals.go +++ b/globals.go @@ -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 (