From b17cdd37a8f03018e0cc1199259a7aa74e2f56a1 Mon Sep 17 00:00:00 2001 From: TJ Holowaychuk Date: Tue, 26 May 2020 10:46:54 +0100 Subject: [PATCH] change FromContext() to always return a logger --- context.go | 10 ++++++---- context_test.go | 13 ++++++------- 2 files changed, 12 insertions(+), 11 deletions(-) diff --git a/context.go b/context.go index 107efd5..290ae41 100644 --- a/context.go +++ b/context.go @@ -10,8 +10,10 @@ func NewContext(ctx context.Context, v Interface) context.Context { return context.WithValue(ctx, logKey{}, v) } -// FromContext returns logger from context. -func FromContext(ctx context.Context) (Interface, bool) { - v, ok := ctx.Value(logKey{}).(Interface) - return v, ok +// FromContext returns the logger from context, or log.Log. +func FromContext(ctx context.Context) Interface { + if v, ok := ctx.Value(logKey{}).(Interface); ok { + return v + } + return Log } diff --git a/context_test.go b/context_test.go index 4a8e25c..a414d21 100644 --- a/context_test.go +++ b/context_test.go @@ -12,13 +12,12 @@ import ( func TestFromContext(t *testing.T) { ctx := context.Background() - logger, ok := log.FromContext(ctx) - assert.False(t, ok) - assert.Nil(t, logger) + logger := log.FromContext(ctx) + assert.Equal(t, log.Log, logger) - ctx = log.NewContext(ctx, log.Log) + logs := log.WithField("foo", "bar") + ctx = log.NewContext(ctx, logs) - logger, ok = log.FromContext(ctx) - assert.True(t, ok) - assert.Equal(t, log.Log, logger) + logger = log.FromContext(ctx) + assert.Equal(t, logs, logger) }