Skip to content

Commit ea9db1c

Browse files
committed
Return L() if no logger is found in the context
1 parent 5cb5101 commit ea9db1c

File tree

2 files changed

+11
-2
lines changed

2 files changed

+11
-2
lines changed

context.go

Lines changed: 7 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -19,10 +19,15 @@ func WithContext(ctx context.Context, logger Logger, args ...interface{}) contex
1919
return context.WithValue(ctx, contextKey, logger)
2020
}
2121

22-
// FromContext returns a logger from the context. This will return nil
23-
// if there is no logger in the context.
22+
// FromContext returns a logger from the context. This will return L()
23+
// (the default logger) if no logger is found in the context. Therefore,
24+
// this will never return a nil value.
2425
func FromContext(ctx context.Context) Logger {
2526
logger, _ := ctx.Value(contextKey).(Logger)
27+
if logger == nil {
28+
return L()
29+
}
30+
2631
return logger
2732
}
2833

context_test.go

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -14,6 +14,10 @@ func TestContext_simpleLogger(t *testing.T) {
1414
require.Equal(t, l, FromContext(ctx))
1515
}
1616

17+
func TestContext_empty(t *testing.T) {
18+
require.Equal(t, L(), FromContext(context.Background()))
19+
}
20+
1721
func TestContext_fields(t *testing.T) {
1822
var buf bytes.Buffer
1923
l := New(&LoggerOptions{

0 commit comments

Comments
 (0)