Skip to content

Commit

Permalink
Race in setting Config.Level (#71)
Browse files Browse the repository at this point in the history
* Race in setting Config.Level: Add failing test

* Fix race

* test shouldn't check for timing
  • Loading branch information
ldemailly authored Oct 2, 2024
1 parent e9a4588 commit 2874c14
Show file tree
Hide file tree
Showing 3 changed files with 20 additions and 1 deletion.
2 changes: 1 addition & 1 deletion http_logging_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -116,7 +116,7 @@ func TestLogAndCall(t *testing.T) {
w.Flush()
actual = b.String()
//nolint: lll
expectedPrefix = `{"level":"info","msg":"test-log-and-call2","method":"","url":"/tea","host":"","proto":"","remote_addr":"","header.x-forwarded-host":"foo2.fortio.org","status":418,"size":5,"microsec":10`
expectedPrefix = `{"level":"info","msg":"test-log-and-call2","method":"","url":"/tea","host":"","proto":"","remote_addr":"","header.x-forwarded-host":"foo2.fortio.org","status":418,"size":5,`
if !strings.HasPrefix(actual, expectedPrefix) {
t.Errorf("unexpected:\n%s\nvs should start with:\n%s\n", actual, expectedPrefix)
}
Expand Down
3 changes: 3 additions & 0 deletions logger.go
Original file line number Diff line number Diff line change
Expand Up @@ -327,7 +327,9 @@ func setLogLevel(lvl Level, logChange bool) Level {
logUnconditionalf(Config.LogFileAndLine, Info, "Log level is now %d %s (was %d %s)", lvl, lvl.String(), prev, prev.String())
}
setLevel(lvl)
jWriter.mutex.Lock()
Config.Level = lvl.String()
jWriter.mutex.Unlock()
}
return prev
}
Expand Down Expand Up @@ -368,6 +370,7 @@ func Logf(lvl Level, format string, rest ...interface{}) {
}

// Used when doing our own logging writing, in JSON/structured mode (and some color variants as well, misnomer).
// Also reusing that lock to update global Config.Level.
var (
jWriter = jsonWriter{w: os.Stderr, tsBuf: make([]byte, 0, 32)}
)
Expand Down
16 changes: 16 additions & 0 deletions logger_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -957,6 +957,22 @@ func TestInvalidFile(t *testing.T) {
}
}

func TestConcurrentLevelSet(t *testing.T) {
// This test is to make sure that setting the log level concurrently
// doesn't cause a -race failure. Shows up in dflag/ for instance with configmap changes.
var wg sync.WaitGroup
wg.Add(int(Fatal - Verbose))
for i := Verbose; i < Fatal; i++ {
go func(lvl Level) {
SetLogLevel(lvl)
wg.Done()
}(i)
}
wg.Wait()
SetLogLevel(Info)
t.Logf("log level is now %s", GetLogLevel().String())
}

// --- Benchmarks

// This `discard` is like io.Discard, except that io.Discard is checked explicitly
Expand Down

0 comments on commit 2874c14

Please sign in to comment.