fix: lock log sink against concurrent write and close (#10668)

fixes #10663
This commit is contained in:
Spike Curtis
2023-11-14 16:38:34 +04:00
committed by GitHub
parent 530be2f96a
commit dc4b1ef406
4 changed files with 101 additions and 5 deletions

38
cli/cliutil/sink.go Normal file
View File

@ -0,0 +1,38 @@
package cliutil
import (
"io"
"sync"
)
type discardAfterClose struct {
sync.Mutex
wc io.WriteCloser
closed bool
}
// DiscardAfterClose is an io.WriteCloser that discards writes after it is closed without errors.
// It is useful as a target for a slog.Sink such that an underlying WriteCloser, like a file, can
// be cleaned up without race conditions from still-active loggers.
func DiscardAfterClose(wc io.WriteCloser) io.WriteCloser {
return &discardAfterClose{wc: wc}
}
func (d *discardAfterClose) Write(p []byte) (n int, err error) {
d.Lock()
defer d.Unlock()
if d.closed {
return len(p), nil
}
return d.wc.Write(p)
}
func (d *discardAfterClose) Close() error {
d.Lock()
defer d.Unlock()
if d.closed {
return nil
}
d.closed = true
return d.wc.Close()
}