Skip to content

Commit

Permalink
Prevent a race condition in testHook
Browse files Browse the repository at this point in the history
The logger could be called from multiple goroutines,
but t.Log() is not designed for.

Signed-off-by: Kazuyoshi Kato <katokazu@amazon.com>
  • Loading branch information
kzys committed Dec 16, 2022
1 parent 544e31c commit 7914280
Showing 1 changed file with 8 additions and 0 deletions.
8 changes: 8 additions & 0 deletions log/logtest/log_hook.go
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@ package logtest

import (
"bytes"
"sync"
"testing"

"github.com/sirupsen/logrus"
Expand All @@ -26,6 +27,7 @@ import (
type testHook struct {
t testing.TB
fmt logrus.Formatter
mu sync.Mutex
}

func (*testHook) Levels() []logrus.Level {
Expand All @@ -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
}

0 comments on commit 7914280

Please sign in to comment.