From 6116a47800b4e2aa477702b415752995a3156b26 Mon Sep 17 00:00:00 2001 From: Jonathan Amsterdam Date: Wed, 5 Apr 2023 06:13:17 -0400 Subject: [PATCH] log/slog: don't call SetDefault in examples Replace the default Logger in some examples with a locally constructed Logger. Calling SetDefault changes global state that could affect other tests. Although we could use a defer to restore the state, that clutters the example and would not work if tests were run concurrently. Change-Id: Ib2595c57f8e6c3e0b39b982f682ba287c2ae249d Reviewed-on: https://go-review.googlesource.com/c/go/+/482475 Run-TryBot: Jonathan Amsterdam TryBot-Result: Gopher Robot Reviewed-by: Alan Donovan --- src/log/slog/example_test.go | 4 +--- src/log/slog/example_wrap_test.go | 14 +++++--------- 2 files changed, 6 insertions(+), 12 deletions(-) diff --git a/src/log/slog/example_test.go b/src/log/slog/example_test.go index 06a2750648..78b60b3649 100644 --- a/src/log/slog/example_test.go +++ b/src/log/slog/example_test.go @@ -17,9 +17,7 @@ func ExampleGroup() { // ... logger := slog.New(slog.HandlerOptions{ReplaceAttr: slogtest.RemoveTime}.NewTextHandler(os.Stdout)) - slog.SetDefault(logger) - - slog.Info("finished", + logger.Info("finished", slog.Group("req", slog.String("method", r.Method), slog.String("url", r.URL.String())), diff --git a/src/log/slog/example_wrap_test.go b/src/log/slog/example_wrap_test.go index 95a493400d..1aad16dc5a 100644 --- a/src/log/slog/example_wrap_test.go +++ b/src/log/slog/example_wrap_test.go @@ -16,20 +16,17 @@ import ( // Infof is an example of a user-defined logging function that wraps slog. // The log record contains the source position of the caller of Infof. -func Infof(format string, args ...any) { - l := slog.Default() - if !l.Enabled(context.Background(), slog.LevelInfo) { +func Infof(logger *slog.Logger, format string, args ...any) { + if !logger.Enabled(context.Background(), slog.LevelInfo) { return } var pcs [1]uintptr runtime.Callers(2, pcs[:]) // skip [Callers, Infof] r := slog.NewRecord(time.Now(), slog.LevelInfo, fmt.Sprintf(format, args...), pcs[0]) - _ = l.Handler().Handle(context.Background(), r) + _ = logger.Handler().Handle(context.Background(), r) } func Example_wrapping() { - defer func(l *slog.Logger) { slog.SetDefault(l) }(slog.Default()) - replace := func(groups []string, a slog.Attr) slog.Attr { // Remove time. if a.Key == slog.TimeKey && len(groups) == 0 { @@ -42,9 +39,8 @@ func Example_wrapping() { return a } logger := slog.New(slog.HandlerOptions{AddSource: true, ReplaceAttr: replace}.NewTextHandler(os.Stdout)) - slog.SetDefault(logger) - Infof("message, %s", "formatted") + Infof(logger, "message, %s", "formatted") // Output: - // level=INFO source=example_wrap_test.go:46 msg="message, formatted" + // level=INFO source=example_wrap_test.go:42 msg="message, formatted" }