Skip to content

Commit

Permalink
[release-branch.go1.9] log: fix data race on log.Output
Browse files Browse the repository at this point in the history
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 <thebrokentoaster@gmail.com>
Run-TryBot: Joe Tsai <thebrokentoaster@gmail.com>
TryBot-Result: Gobot Gobot <gobot@golang.org>
Reviewed-on: https://go-review.googlesource.com/70976
Run-TryBot: Russ Cox <rsc@golang.org>
  • Loading branch information
hagen1778 authored and rsc committed Oct 25, 2017
1 parent 0b55d8d commit bd34e74
Show file tree
Hide file tree
Showing 2 changed files with 12 additions and 5 deletions.
6 changes: 1 addition & 5 deletions src/log/log.go
Original file line number Diff line number Diff line change
Expand Up @@ -147,11 +147,7 @@ func (l *Logger) formatHeader(buf *[]byte, t time.Time, file string, line int) {
// provided for generality, although at the moment on all pre-defined
// paths it will be 2.
func (l *Logger) Output(calldepth int, s string) error {
// Get time early if we need it.
var now time.Time
if l.flag&(Ldate|Ltime|Lmicroseconds) != 0 {
now = time.Now()
}
now := time.Now() // get this early.
var file string
var line int
l.mu.Lock()
Expand Down
11 changes: 11 additions & 0 deletions src/log/log_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -88,6 +88,17 @@ func TestOutput(t *testing.T) {
}
}

func TestOutputRace(t *testing.T) {
var b bytes.Buffer
l := New(&b, "", 0)
for i := 0; i < 100; i++ {
go func() {
l.SetFlags(0)
}()
l.Output(0, "")
}
}

func TestFlagAndPrefixSetting(t *testing.T) {
var b bytes.Buffer
l := New(&b, "Test:", LstdFlags)
Expand Down

0 comments on commit bd34e74

Please sign in to comment.