log: fix data race in RotatingFileHandler

This commit is contained in:
Zhao Li 2018-09-13 18:10:27 +08:00
parent ff3a5d24d2
commit 20cb3e3549

View file

@ -77,8 +77,9 @@ func FileHandler(path string, fmtr Format) (Handler, error) {
// countingWriter wraps a WriteCloser object in order to count the written bytes. // countingWriter wraps a WriteCloser object in order to count the written bytes.
type countingWriter struct { type countingWriter struct {
w io.WriteCloser // the wrapped object sync.Mutex // lock
count uint // number of bytes written w io.WriteCloser // the wrapped object
count uint // number of bytes written
} }
// Write increments the byte counter by the number of bytes written. // Write increments the byte counter by the number of bytes written.
@ -157,9 +158,14 @@ func RotatingFileHandler(path string, limit uint, formatter Format) (Handler, er
if counter == nil { if counter == nil {
counter = new(countingWriter) counter = new(countingWriter)
} }
h := StreamHandler(counter, formatter) h := LazyHandler(FuncHandler(func(r *Record) error {
_, err := counter.Write(formatter.Format(r))
return err
}))
return FuncHandler(func(r *Record) error { return FuncHandler(func(r *Record) error {
counter.Lock()
defer counter.Unlock()
if counter.count > limit { if counter.count > limit {
counter.Close() counter.Close()
counter.w = nil counter.w = nil