Skip to content

Commit bd34e74

Browse files
hagen1778rsc
authored andcommitted
[release-branch.go1.9] log: fix data race on log.Output
There was unprotected access to Logger.flag in log.Output which could lead to data race in cases when log.SetFlags called simultaneously. For example, "hot" switching on/off debug-mode for Logger by log.SetFlags while application still writing logs. Fixes #21935 Change-Id: I36be25f23cad44cde62ed1af28a30d276400e1b8 Reviewed-on: https://go-review.googlesource.com/64710 Reviewed-by: Joe Tsai <[email protected]> Run-TryBot: Joe Tsai <[email protected]> TryBot-Result: Gobot Gobot <[email protected]> Reviewed-on: https://go-review.googlesource.com/70976 Run-TryBot: Russ Cox <[email protected]>
1 parent 0b55d8d commit bd34e74

File tree

2 files changed

+12
-5
lines changed

2 files changed

+12
-5
lines changed

src/log/log.go

Lines changed: 1 addition & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -147,11 +147,7 @@ func (l *Logger) formatHeader(buf *[]byte, t time.Time, file string, line int) {
147147
// provided for generality, although at the moment on all pre-defined
148148
// paths it will be 2.
149149
func (l *Logger) Output(calldepth int, s string) error {
150-
// Get time early if we need it.
151-
var now time.Time
152-
if l.flag&(Ldate|Ltime|Lmicroseconds) != 0 {
153-
now = time.Now()
154-
}
150+
now := time.Now() // get this early.
155151
var file string
156152
var line int
157153
l.mu.Lock()

src/log/log_test.go

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -88,6 +88,17 @@ func TestOutput(t *testing.T) {
8888
}
8989
}
9090

91+
func TestOutputRace(t *testing.T) {
92+
var b bytes.Buffer
93+
l := New(&b, "", 0)
94+
for i := 0; i < 100; i++ {
95+
go func() {
96+
l.SetFlags(0)
97+
}()
98+
l.Output(0, "")
99+
}
100+
}
101+
91102
func TestFlagAndPrefixSetting(t *testing.T) {
92103
var b bytes.Buffer
93104
l := New(&b, "Test:", LstdFlags)

0 commit comments

Comments
 (0)