Skip to content

Commit d8c31b4

Browse files
committed
fix race condition in testlogger
1 parent fd4b484 commit d8c31b4

File tree

1 file changed

+25
-4
lines changed

1 file changed

+25
-4
lines changed

logger.go

Lines changed: 25 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -6,6 +6,7 @@ import (
66
"log"
77
"strconv"
88
"strings"
9+
"sync"
910
)
1011

1112
type StdLogger interface {
@@ -32,12 +33,32 @@ func (n nopLogger) Debug(_ string, _ ...LogField) {}
3233

3334
type testLogger struct {
3435
capture bytes.Buffer
36+
mu sync.Mutex
3537
}
3638

37-
func (l *testLogger) Print(v ...interface{}) { fmt.Fprint(&l.capture, v...) }
38-
func (l *testLogger) Printf(format string, v ...interface{}) { fmt.Fprintf(&l.capture, format, v...) }
39-
func (l *testLogger) Println(v ...interface{}) { fmt.Fprintln(&l.capture, v...) }
40-
func (l *testLogger) String() string { return l.capture.String() }
39+
func (l *testLogger) Print(v ...interface{}) {
40+
l.mu.Lock()
41+
defer l.mu.Unlock()
42+
fmt.Fprint(&l.capture, v...)
43+
}
44+
45+
func (l *testLogger) Printf(format string, v ...interface{}) {
46+
l.mu.Lock()
47+
defer l.mu.Unlock()
48+
fmt.Fprintf(&l.capture, format, v...)
49+
}
50+
51+
func (l *testLogger) Println(v ...interface{}) {
52+
l.mu.Lock()
53+
defer l.mu.Unlock()
54+
fmt.Fprintln(&l.capture, v...)
55+
}
56+
57+
func (l *testLogger) String() string {
58+
l.mu.Lock()
59+
defer l.mu.Unlock()
60+
return l.capture.String()
61+
}
4162

4263
type defaultLogger struct{}
4364

0 commit comments

Comments
 (0)