log: share mutex in log handles with same writer and other fields (#35074)
Some checks are pending
/ Linux Build (push) Waiting to run
/ Linux Build (arm) (push) Waiting to run
/ Keeper Build (push) Waiting to run
/ Windows Build (push) Waiting to run
/ Docker Image (push) Waiting to run

In old code, mu is struct not pointer, it caused create new mutex event
with same writer. Change to use pointer to sync.Mutex, so that the mutex
is shared between handler with same writer.
This commit is contained in:
cui 2026-06-11 04:37:39 +08:00 committed by GitHub
parent 8a8becaeab
commit eea6242742
No known key found for this signature in database
GPG key ID: B5690EEEBB952194

View file

@ -37,7 +37,7 @@ func (h *discardHandler) WithAttrs(attrs []slog.Attr) slog.Handler {
} }
type TerminalHandler struct { type TerminalHandler struct {
mu sync.Mutex mu *sync.Mutex
wr io.Writer wr io.Writer
lvl slog.Level lvl slog.Level
useColor bool useColor bool
@ -66,6 +66,7 @@ func NewTerminalHandler(wr io.Writer, useColor bool) *TerminalHandler {
// records which are less than or equal to the specified verbosity level. // records which are less than or equal to the specified verbosity level.
func NewTerminalHandlerWithLevel(wr io.Writer, lvl slog.Level, useColor bool) *TerminalHandler { func NewTerminalHandlerWithLevel(wr io.Writer, lvl slog.Level, useColor bool) *TerminalHandler {
return &TerminalHandler{ return &TerminalHandler{
mu: &sync.Mutex{},
wr: wr, wr: wr,
lvl: lvl, lvl: lvl,
useColor: useColor, useColor: useColor,
@ -92,6 +93,7 @@ func (h *TerminalHandler) WithGroup(name string) slog.Handler {
func (h *TerminalHandler) WithAttrs(attrs []slog.Attr) slog.Handler { func (h *TerminalHandler) WithAttrs(attrs []slog.Attr) slog.Handler {
return &TerminalHandler{ return &TerminalHandler{
mu: h.mu,
wr: h.wr, wr: h.wr,
lvl: h.lvl, lvl: h.lvl,
useColor: h.useColor, useColor: h.useColor,