From 791428005f18033330ea77316e67f738040ca6c4 Mon Sep 17 00:00:00 2001 From: Kazuyoshi Kato Date: Fri, 16 Dec 2022 23:47:44 +0000 Subject: [PATCH] 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 --- log/logtest/log_hook.go | 8 ++++++++ 1 file changed, 8 insertions(+) diff --git a/log/logtest/log_hook.go b/log/logtest/log_hook.go index 2e842cd5011f..f865e39e4751 100644 --- a/log/logtest/log_hook.go +++ b/log/logtest/log_hook.go @@ -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 }