From fbdc814b1be1f4966f8ae30a43da56ec25001b8e Mon Sep 17 00:00:00 2001 From: Martin Kobetic Date: Sat, 23 Jul 2022 08:12:56 -0400 Subject: [PATCH] fix: logging.From panic (#268) --- logging/context.go | 6 ++++-- logging/context_test.go | 21 +++++++++++++++++++++ 2 files changed, 25 insertions(+), 2 deletions(-) create mode 100644 logging/context_test.go diff --git a/logging/context.go b/logging/context.go index 1484efaf..bac2d90f 100644 --- a/logging/context.go +++ b/logging/context.go @@ -8,9 +8,11 @@ import ( var logKey = &struct{}{} -// From allows retrieving the Logger from a Context +// From allows retrieving the Logger from a Context. +// Returns nil if Context does not have one. func From(ctx context.Context) *zap.Logger { - return ctx.Value(logKey).(*zap.Logger) + logger, _ := ctx.Value(logKey).(*zap.Logger) + return logger } // With associates a Logger with a Context to allow passing diff --git a/logging/context_test.go b/logging/context_test.go new file mode 100644 index 00000000..1f93881e --- /dev/null +++ b/logging/context_test.go @@ -0,0 +1,21 @@ +package logging + +import ( + "context" + "testing" + + "github.com/stretchr/testify/require" + "go.uber.org/zap" +) + +func Test_EmptyContext(t *testing.T) { + logger := From(context.Background()) + require.Nil(t, logger) +} + +func Test_With(t *testing.T) { + logger, err := zap.NewDevelopment() + require.NoError(t, err) + ctx := With(context.Background(), logger) + require.Equal(t, logger, From(ctx)) +}