From 20cb3e3549e66eb5039e3d3eafc991242a41f741 Mon Sep 17 00:00:00 2001 From: Zhao Li Date: Thu, 13 Sep 2018 18:10:27 +0800 Subject: [PATCH] log: fix data race in RotatingFileHandler --- log/handler.go | 12 +++++++++--- 1 file changed, 9 insertions(+), 3 deletions(-) diff --git a/log/handler.go b/log/handler.go index 2f01b5dc6f..e3157438dd 100644 --- a/log/handler.go +++ b/log/handler.go @@ -77,8 +77,9 @@ func FileHandler(path string, fmtr Format) (Handler, error) { // countingWriter wraps a WriteCloser object in order to count the written bytes. type countingWriter struct { - w io.WriteCloser // the wrapped object - count uint // number of bytes written + sync.Mutex // lock + w io.WriteCloser // the wrapped object + count uint // 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 { 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 { + counter.Lock() + defer counter.Unlock() if counter.count > limit { counter.Close() counter.w = nil