Skip to content

Commit

Permalink
change FromContext() to always return a logger
Browse files Browse the repository at this point in the history
  • Loading branch information
tj committed May 26, 2020
1 parent 35888a9 commit b17cdd3
Show file tree
Hide file tree
Showing 2 changed files with 12 additions and 11 deletions.
10 changes: 6 additions & 4 deletions context.go
Original file line number Diff line number Diff line change
Expand Up @@ -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
}
13 changes: 6 additions & 7 deletions context_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -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)
}

0 comments on commit b17cdd3

Please sign in to comment.