internal/testlog: clone attrs before appending

WithAttrs and terminalFormat appended to h.attrs directly, which can
mutate the shared slice when it has spare capacity. Clone attrs first
to avoid corrupting parent handler state.
This commit is contained in:
Weixie Cui 2026-07-09 12:15:00 +08:00
parent 6c80ee6c50
commit 164eeb84c0

View file

@ -22,6 +22,7 @@ import (
"context" "context"
"fmt" "fmt"
"log/slog" "log/slog"
"slices"
"sync" "sync"
"github.com/ethereum/go-ethereum/log" "github.com/ethereum/go-ethereum/log"
@ -76,7 +77,7 @@ func (h *bufHandler) WithAttrs(attrs []slog.Attr) slog.Handler {
copy(records[:], h.buf[:]) copy(records[:], h.buf[:])
return &bufHandler{ return &bufHandler{
buf: records, buf: records,
attrs: append(h.attrs, attrs...), attrs: append(slices.Clone(h.attrs), attrs...),
level: h.level, level: h.level,
} }
} }
@ -186,7 +187,7 @@ func (h *bufHandler) terminalFormat(r slog.Record) string {
return true return true
}) })
attrs = append(h.attrs, attrs...) attrs = append(slices.Clone(h.attrs), attrs...)
fmt.Fprintf(buf, "%s[%s] %s ", lvl, r.Time.Format(termTimeFormat), r.Message) fmt.Fprintf(buf, "%s[%s] %s ", lvl, r.Time.Format(termTimeFormat), r.Message)
if length := len(r.Message); length < 40 { if length := len(r.Message); length < 40 {