Prevent a race condition in testHook

The logger could be called from multiple goroutines,
but t.Log() is not designed for.

Signed-off-by: Kazuyoshi Kato <katokazu@amazon.com>
This commit is contained in:
Kazuyoshi Kato 2022-12-16 23:47:44 +00:00
parent 544e31c426
commit 791428005f

View File

@ -18,6 +18,7 @@ package logtest
import (
"bytes"
"sync"
"testing"
"github.com/sirupsen/logrus"
@ -26,6 +27,7 @@ import (
type testHook struct {
t testing.TB
fmt logrus.Formatter
mu sync.Mutex
}
func (*testHook) Levels() []logrus.Level {
@ -37,6 +39,12 @@ func (h *testHook) Fire(e *logrus.Entry) error {
if err != nil {
return err
}
// Because the logger could be called from multiple goroutines,
// but t.Log() is not designed for.
h.mu.Lock()
defer h.mu.Unlock()
h.t.Log(string(bytes.TrimRight(s, "\n")))
return nil
}