Skip to content

Commit 6518697

Browse files
committed
log/slog: replace nil contexts with context.Background()
Passing nil for a context is discouraged. We should avoid it. Fixes #61219. Change-Id: I664387070aacb56af580b6b0791ca40982d2a711 Reviewed-on: https://go-review.googlesource.com/c/go/+/508437 Run-TryBot: Jonathan Amsterdam <[email protected]> TryBot-Result: Gopher Robot <[email protected]> Reviewed-by: Alan Donovan <[email protected]>
1 parent 3f8b04b commit 6518697

File tree

6 files changed

+42
-37
lines changed

6 files changed

+42
-37
lines changed

src/log/slog/doc.go

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -206,7 +206,7 @@ keys and values; this allows it, too, to avoid allocation.
206206
207207
The call
208208
209-
logger.LogAttrs(nil, slog.LevelInfo, "hello", slog.Int("count", 3))
209+
logger.LogAttrs(ctx, slog.LevelInfo, "hello", slog.Int("count", 3))
210210
211211
is the most efficient way to achieve the same output as
212212

src/log/slog/example_custom_levels_test.go

Lines changed: 5 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,7 @@
55
package slog_test
66

77
import (
8+
"context"
89
"log/slog"
910
"os"
1011
)
@@ -72,13 +73,14 @@ func ExampleHandlerOptions_customLevels() {
7273
})
7374

7475
logger := slog.New(th)
75-
logger.Log(nil, LevelEmergency, "missing pilots")
76+
ctx := context.Background()
77+
logger.Log(ctx, LevelEmergency, "missing pilots")
7678
logger.Error("failed to start engines", "err", "missing fuel")
7779
logger.Warn("falling back to default value")
78-
logger.Log(nil, LevelNotice, "all systems are running")
80+
logger.Log(ctx, LevelNotice, "all systems are running")
7981
logger.Info("initiating launch")
8082
logger.Debug("starting background job")
81-
logger.Log(nil, LevelTrace, "button clicked")
83+
logger.Log(ctx, LevelTrace, "button clicked")
8284

8385
// Output:
8486
// sev=EMERGENCY msg="missing pilots"

src/log/slog/handler_test.go

Lines changed: 1 addition & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -108,8 +108,6 @@ func TestDefaultHandle(t *testing.T) {
108108

109109
// Verify the common parts of TextHandler and JSONHandler.
110110
func TestJSONAndTextHandlers(t *testing.T) {
111-
ctx := context.Background()
112-
113111
// remove all Attrs
114112
removeAll := func(_ []string, a Attr) Attr { return Attr{} }
115113

@@ -412,7 +410,7 @@ func TestJSONAndTextHandlers(t *testing.T) {
412410
h = test.with(h)
413411
}
414412
buf.Reset()
415-
if err := h.Handle(ctx, r); err != nil {
413+
if err := h.Handle(nil, r); err != nil {
416414
t.Fatal(err)
417415
}
418416
want := strings.ReplaceAll(handler.want, "$LINE", line)

src/log/slog/json_handler_test.go

Lines changed: 4 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -174,6 +174,7 @@ func BenchmarkJSONHandler(b *testing.B) {
174174
}},
175175
} {
176176
b.Run(bench.name, func(b *testing.B) {
177+
ctx := context.Background()
177178
l := New(NewJSONHandler(io.Discard, &bench.opts)).With(
178179
String("program", "my-test-program"),
179180
String("package", "log/slog"),
@@ -182,7 +183,7 @@ func BenchmarkJSONHandler(b *testing.B) {
182183
b.ReportAllocs()
183184
b.ResetTimer()
184185
for i := 0; i < b.N; i++ {
185-
l.LogAttrs(nil, LevelInfo, "this is a typical log message",
186+
l.LogAttrs(ctx, LevelInfo, "this is a typical log message",
186187
String("module", "github.com/google/go-cmp"),
187188
String("version", "v1.23.4"),
188189
Int("count", 23),
@@ -238,12 +239,13 @@ func BenchmarkPreformatting(b *testing.B) {
238239
{"struct", io.Discard, structAttrs},
239240
{"struct file", outFile, structAttrs},
240241
} {
242+
ctx := context.Background()
241243
b.Run(bench.name, func(b *testing.B) {
242244
l := New(NewJSONHandler(bench.wc, nil)).With(bench.attrs...)
243245
b.ReportAllocs()
244246
b.ResetTimer()
245247
for i := 0; i < b.N; i++ {
246-
l.LogAttrs(nil, LevelInfo, "this is a typical log message",
248+
l.LogAttrs(ctx, LevelInfo, "this is a typical log message",
247249
String("module", "github.com/google/go-cmp"),
248250
String("version", "v1.23.4"),
249251
Int("count", 23),

src/log/slog/logger.go

Lines changed: 8 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -165,7 +165,7 @@ func (l *Logger) LogAttrs(ctx context.Context, level Level, msg string, attrs ..
165165

166166
// Debug logs at LevelDebug.
167167
func (l *Logger) Debug(msg string, args ...any) {
168-
l.log(nil, LevelDebug, msg, args...)
168+
l.log(context.Background(), LevelDebug, msg, args...)
169169
}
170170

171171
// DebugContext logs at LevelDebug with the given context.
@@ -175,7 +175,7 @@ func (l *Logger) DebugContext(ctx context.Context, msg string, args ...any) {
175175

176176
// Info logs at LevelInfo.
177177
func (l *Logger) Info(msg string, args ...any) {
178-
l.log(nil, LevelInfo, msg, args...)
178+
l.log(context.Background(), LevelInfo, msg, args...)
179179
}
180180

181181
// InfoContext logs at LevelInfo with the given context.
@@ -185,7 +185,7 @@ func (l *Logger) InfoContext(ctx context.Context, msg string, args ...any) {
185185

186186
// Warn logs at LevelWarn.
187187
func (l *Logger) Warn(msg string, args ...any) {
188-
l.log(nil, LevelWarn, msg, args...)
188+
l.log(context.Background(), LevelWarn, msg, args...)
189189
}
190190

191191
// WarnContext logs at LevelWarn with the given context.
@@ -195,7 +195,7 @@ func (l *Logger) WarnContext(ctx context.Context, msg string, args ...any) {
195195

196196
// Error logs at LevelError.
197197
func (l *Logger) Error(msg string, args ...any) {
198-
l.log(nil, LevelError, msg, args...)
198+
l.log(context.Background(), LevelError, msg, args...)
199199
}
200200

201201
// ErrorContext logs at LevelError with the given context.
@@ -247,7 +247,7 @@ func (l *Logger) logAttrs(ctx context.Context, level Level, msg string, attrs ..
247247

248248
// Debug calls Logger.Debug on the default logger.
249249
func Debug(msg string, args ...any) {
250-
Default().log(nil, LevelDebug, msg, args...)
250+
Default().log(context.Background(), LevelDebug, msg, args...)
251251
}
252252

253253
// DebugContext calls Logger.DebugContext on the default logger.
@@ -257,7 +257,7 @@ func DebugContext(ctx context.Context, msg string, args ...any) {
257257

258258
// Info calls Logger.Info on the default logger.
259259
func Info(msg string, args ...any) {
260-
Default().log(nil, LevelInfo, msg, args...)
260+
Default().log(context.Background(), LevelInfo, msg, args...)
261261
}
262262

263263
// InfoContext calls Logger.InfoContext on the default logger.
@@ -267,7 +267,7 @@ func InfoContext(ctx context.Context, msg string, args ...any) {
267267

268268
// Warn calls Logger.Warn on the default logger.
269269
func Warn(msg string, args ...any) {
270-
Default().log(nil, LevelWarn, msg, args...)
270+
Default().log(context.Background(), LevelWarn, msg, args...)
271271
}
272272

273273
// WarnContext calls Logger.WarnContext on the default logger.
@@ -277,7 +277,7 @@ func WarnContext(ctx context.Context, msg string, args ...any) {
277277

278278
// Error calls Logger.Error on the default logger.
279279
func Error(msg string, args ...any) {
280-
Default().log(nil, LevelError, msg, args...)
280+
Default().log(context.Background(), LevelError, msg, args...)
281281
}
282282

283283
// ErrorContext calls Logger.ErrorContext on the default logger.

src/log/slog/logger_test.go

Lines changed: 23 additions & 20 deletions
Original file line numberDiff line numberDiff line change
@@ -25,6 +25,7 @@ import (
2525
const timeRE = `\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}\.\d{3}(Z|[+-]\d{2}:\d{2})`
2626

2727
func TestLogTextHandler(t *testing.T) {
28+
ctx := context.Background()
2829
var buf bytes.Buffer
2930

3031
l := New(NewTextHandler(&buf, nil))
@@ -51,10 +52,10 @@ func TestLogTextHandler(t *testing.T) {
5152
l.Error("bad", "a", 1)
5253
check(`level=ERROR msg=bad a=1`)
5354

54-
l.Log(nil, LevelWarn+1, "w", Int("a", 1), String("b", "two"))
55+
l.Log(ctx, LevelWarn+1, "w", Int("a", 1), String("b", "two"))
5556
check(`level=WARN\+1 msg=w a=1 b=two`)
5657

57-
l.LogAttrs(nil, LevelInfo+1, "a b c", Int("a", 1), String("b", "two"))
58+
l.LogAttrs(ctx, LevelInfo+1, "a b c", Int("a", 1), String("b", "two"))
5859
check(`level=INFO\+1 msg="a b c" a=1 b=two`)
5960

6061
l.Info("info", "a", []Attr{Int("i", 1)})
@@ -156,6 +157,7 @@ func TestAttrs(t *testing.T) {
156157
}
157158

158159
func TestCallDepth(t *testing.T) {
160+
ctx := context.Background()
159161
h := &captureHandler{}
160162
var startLine int
161163

@@ -181,9 +183,9 @@ func TestCallDepth(t *testing.T) {
181183
startLine = f.Line + 4
182184
// Do not change the number of lines between here and the call to check(0).
183185

184-
logger.Log(nil, LevelInfo, "")
186+
logger.Log(ctx, LevelInfo, "")
185187
check(0)
186-
logger.LogAttrs(nil, LevelInfo, "")
188+
logger.LogAttrs(ctx, LevelInfo, "")
187189
check(1)
188190
logger.Debug("")
189191
check(2)
@@ -201,13 +203,14 @@ func TestCallDepth(t *testing.T) {
201203
check(8)
202204
Error("")
203205
check(9)
204-
Log(nil, LevelInfo, "")
206+
Log(ctx, LevelInfo, "")
205207
check(10)
206-
LogAttrs(nil, LevelInfo, "")
208+
LogAttrs(ctx, LevelInfo, "")
207209
check(11)
208210
}
209211

210212
func TestAlloc(t *testing.T) {
213+
ctx := context.Background()
211214
dl := New(discardHandler{})
212215
defer SetDefault(Default()) // restore
213216
SetDefault(dl)
@@ -222,7 +225,7 @@ func TestAlloc(t *testing.T) {
222225
wantAllocs(t, 0, func() { dl.Info("hello") })
223226
})
224227
t.Run("logger.Log", func(t *testing.T) {
225-
wantAllocs(t, 0, func() { dl.Log(nil, LevelDebug, "hello") })
228+
wantAllocs(t, 0, func() { dl.Log(ctx, LevelDebug, "hello") })
226229
})
227230
t.Run("2 pairs", func(t *testing.T) {
228231
s := "abc"
@@ -239,7 +242,7 @@ func TestAlloc(t *testing.T) {
239242
s := "abc"
240243
i := 2000
241244
wantAllocs(t, 2, func() {
242-
l.Log(nil, LevelInfo, "hello",
245+
l.Log(ctx, LevelInfo, "hello",
243246
"n", i,
244247
"s", s,
245248
)
@@ -250,8 +253,8 @@ func TestAlloc(t *testing.T) {
250253
s := "abc"
251254
i := 2000
252255
wantAllocs(t, 0, func() {
253-
if l.Enabled(nil, LevelInfo) {
254-
l.Log(nil, LevelInfo, "hello",
256+
if l.Enabled(ctx, LevelInfo) {
257+
l.Log(ctx, LevelInfo, "hello",
255258
"n", i,
256259
"s", s,
257260
)
@@ -273,30 +276,30 @@ func TestAlloc(t *testing.T) {
273276
wantAllocs(t, 0, func() { dl.Info("", "error", io.EOF) })
274277
})
275278
t.Run("attrs1", func(t *testing.T) {
276-
wantAllocs(t, 0, func() { dl.LogAttrs(nil, LevelInfo, "", Int("a", 1)) })
277-
wantAllocs(t, 0, func() { dl.LogAttrs(nil, LevelInfo, "", Any("error", io.EOF)) })
279+
wantAllocs(t, 0, func() { dl.LogAttrs(ctx, LevelInfo, "", Int("a", 1)) })
280+
wantAllocs(t, 0, func() { dl.LogAttrs(ctx, LevelInfo, "", Any("error", io.EOF)) })
278281
})
279282
t.Run("attrs3", func(t *testing.T) {
280283
wantAllocs(t, 0, func() {
281-
dl.LogAttrs(nil, LevelInfo, "hello", Int("a", 1), String("b", "two"), Duration("c", time.Second))
284+
dl.LogAttrs(ctx, LevelInfo, "hello", Int("a", 1), String("b", "two"), Duration("c", time.Second))
282285
})
283286
})
284287
t.Run("attrs3 disabled", func(t *testing.T) {
285288
logger := New(discardHandler{disabled: true})
286289
wantAllocs(t, 0, func() {
287-
logger.LogAttrs(nil, LevelInfo, "hello", Int("a", 1), String("b", "two"), Duration("c", time.Second))
290+
logger.LogAttrs(ctx, LevelInfo, "hello", Int("a", 1), String("b", "two"), Duration("c", time.Second))
288291
})
289292
})
290293
t.Run("attrs6", func(t *testing.T) {
291294
wantAllocs(t, 1, func() {
292-
dl.LogAttrs(nil, LevelInfo, "hello",
295+
dl.LogAttrs(ctx, LevelInfo, "hello",
293296
Int("a", 1), String("b", "two"), Duration("c", time.Second),
294297
Int("d", 1), String("e", "two"), Duration("f", time.Second))
295298
})
296299
})
297300
t.Run("attrs9", func(t *testing.T) {
298301
wantAllocs(t, 1, func() {
299-
dl.LogAttrs(nil, LevelInfo, "hello",
302+
dl.LogAttrs(ctx, LevelInfo, "hello",
300303
Int("a", 1), String("b", "two"), Duration("c", time.Second),
301304
Int("d", 1), String("e", "two"), Duration("f", time.Second),
302305
Int("d", 1), String("e", "two"), Duration("f", time.Second))
@@ -511,27 +514,27 @@ func BenchmarkNopLog(b *testing.B) {
511514
b.Run("no attrs", func(b *testing.B) {
512515
b.ReportAllocs()
513516
for i := 0; i < b.N; i++ {
514-
l.LogAttrs(nil, LevelInfo, "msg")
517+
l.LogAttrs(ctx, LevelInfo, "msg")
515518
}
516519
})
517520
b.Run("attrs", func(b *testing.B) {
518521
b.ReportAllocs()
519522
for i := 0; i < b.N; i++ {
520-
l.LogAttrs(nil, LevelInfo, "msg", Int("a", 1), String("b", "two"), Bool("c", true))
523+
l.LogAttrs(ctx, LevelInfo, "msg", Int("a", 1), String("b", "two"), Bool("c", true))
521524
}
522525
})
523526
b.Run("attrs-parallel", func(b *testing.B) {
524527
b.ReportAllocs()
525528
b.RunParallel(func(pb *testing.PB) {
526529
for pb.Next() {
527-
l.LogAttrs(nil, LevelInfo, "msg", Int("a", 1), String("b", "two"), Bool("c", true))
530+
l.LogAttrs(ctx, LevelInfo, "msg", Int("a", 1), String("b", "two"), Bool("c", true))
528531
}
529532
})
530533
})
531534
b.Run("keys-values", func(b *testing.B) {
532535
b.ReportAllocs()
533536
for i := 0; i < b.N; i++ {
534-
l.Log(nil, LevelInfo, "msg", "a", 1, "b", "two", "c", true)
537+
l.Log(ctx, LevelInfo, "msg", "a", 1, "b", "two", "c", true)
535538
}
536539
})
537540
b.Run("WithContext", func(b *testing.B) {

0 commit comments

Comments
 (0)