Merge pull request #15562 from tjhop/fix/dedupe-logger-concurrent-map-panic

fix(deduper): use ptr to sync.RWMutex, fix panic during concurrent use
pull/13423/merge
Bartlomiej Plotka 2024-12-10 09:27:24 +01:00 committed by GitHub
commit a70cba84a6
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
2 changed files with 28 additions and 1 deletions

View File

@ -33,7 +33,7 @@ type Deduper struct {
next *slog.Logger
repeat time.Duration
quit chan struct{}
mtx sync.RWMutex
mtx *sync.RWMutex
seen map[string]time.Time
}
@ -43,6 +43,7 @@ func Dedupe(next *slog.Logger, repeat time.Duration) *Deduper {
next: next,
repeat: repeat,
quit: make(chan struct{}),
mtx: new(sync.RWMutex),
seen: map[string]time.Time{},
}
go d.run()
@ -88,6 +89,7 @@ func (d *Deduper) WithAttrs(attrs []slog.Attr) slog.Handler {
repeat: d.repeat,
quit: d.quit,
seen: d.seen,
mtx: d.mtx,
}
}
@ -103,6 +105,7 @@ func (d *Deduper) WithGroup(name string) slog.Handler {
repeat: d.repeat,
quit: d.quit,
seen: d.seen,
mtx: d.mtx,
}
}

View File

@ -56,3 +56,27 @@ func TestDedupe(t *testing.T) {
}
require.Len(t, lines, 2)
}
func TestDedupeConcurrent(t *testing.T) {
d := Dedupe(promslog.New(&promslog.Config{}), 250*time.Millisecond)
dlog := slog.New(d)
defer d.Stop()
concurrentWriteFunc := func() {
go func() {
dlog1 := dlog.With("writer", 1)
for i := 0; i < 10; i++ {
dlog1.With("foo", "bar").Info("test", "hello", "world")
}
}()
go func() {
dlog2 := dlog.With("writer", 2)
for i := 0; i < 10; i++ {
dlog2.With("foo", "bar").Info("test", "hello", "world")
}
}()
}
require.NotPanics(t, func() { concurrentWriteFunc() })
}