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)) +}