]> Cypherpunks repositories - gostls13.git/commitdiff
log/slog: log and logAttrs initialize ctx at top
author喜欢 <csharpwz@outlook.com>
Fri, 28 Mar 2025 06:39:41 +0000 (06:39 +0000)
committerJonathan Amsterdam <jba@google.com>
Tue, 1 Apr 2025 13:38:57 +0000 (06:38 -0700)
In extreme cases (e.g., ctx = nil), it is recommended to initialize the
context only once at the entry point before using log and logAttrs.

Change-Id: Ib191963f52183406d7fcd5104b60fea1a9e1bc80
GitHub-Last-Rev: e1719b95390011a45a0a6652a13e675279bc76cd
GitHub-Pull-Request: golang/go#73066
Reviewed-on: https://go-review.googlesource.com/c/go/+/661255
Reviewed-by: Carlos Amedee <carlos@golang.org>
Reviewed-by: Jonathan Amsterdam <jba@google.com>
LUCI-TryBot-Result: Go LUCI <golang-scoped@luci-project-accounts.iam.gserviceaccount.com>

src/log/slog/logger.go

index 961e0cd2cec67e244b5d78eb34ee27a1238816af..69e1cf9f1528603de00ab937596e348fbeddb1a5 100644 (file)
@@ -238,6 +238,9 @@ func (l *Logger) ErrorContext(ctx context.Context, msg string, args ...any) {
 // It must always be called directly by an exported logging method
 // or function, because it uses a fixed call depth to obtain the pc.
 func (l *Logger) log(ctx context.Context, level Level, msg string, args ...any) {
+       if ctx == nil {
+               ctx = context.Background()
+       }
        if !l.Enabled(ctx, level) {
                return
        }
@@ -250,14 +253,14 @@ func (l *Logger) log(ctx context.Context, level Level, msg string, args ...any)
        }
        r := NewRecord(time.Now(), level, msg, pc)
        r.Add(args...)
-       if ctx == nil {
-               ctx = context.Background()
-       }
        _ = l.Handler().Handle(ctx, r)
 }
 
 // logAttrs is like [Logger.log], but for methods that take ...Attr.
 func (l *Logger) logAttrs(ctx context.Context, level Level, msg string, attrs ...Attr) {
+       if ctx == nil {
+               ctx = context.Background()
+       }
        if !l.Enabled(ctx, level) {
                return
        }
@@ -270,9 +273,6 @@ func (l *Logger) logAttrs(ctx context.Context, level Level, msg string, attrs ..
        }
        r := NewRecord(time.Now(), level, msg, pc)
        r.AddAttrs(attrs...)
-       if ctx == nil {
-               ctx = context.Background()
-       }
        _ = l.Handler().Handle(ctx, r)
 }