From e1719b95390011a45a0a6652a13e675279bc76cd Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E5=96=9C=E6=AC=A2?= Date: Thu, 27 Mar 2025 16:51:33 +0800 Subject: [PATCH] log/slog: log/logAttrs after single ctx initialization In extreme cases (ctx = nil), it is recommended to initialize the context only once at the entry point of the log/logAttrs. --- src/log/slog/logger.go | 12 ++++++------ 1 file changed, 6 insertions(+), 6 deletions(-) diff --git a/src/log/slog/logger.go b/src/log/slog/logger.go index 961e0cd2ce..69e1cf9f15 100644 --- a/src/log/slog/logger.go +++ b/src/log/slog/logger.go @@ -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) }