Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix race condition AddHook and traces #1234

Merged
merged 1 commit into from Feb 18, 2021
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
10 changes: 9 additions & 1 deletion entry.go
Expand Up @@ -261,7 +261,15 @@ func (entry *Entry) log(level Level, msg string) {
}

func (entry *Entry) fireHooks() {
err := entry.Logger.Hooks.Fire(entry.Level, entry)
var tmpHooks LevelHooks
entry.Logger.mu.Lock()
tmpHooks = make(LevelHooks, len(entry.Logger.Hooks))
for k, v := range entry.Logger.Hooks {
tmpHooks[k] = v
}
entry.Logger.mu.Unlock()
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This could be simplified:

entry.Logger.mu.Lock()
tmpHooks := append(LevelHooks(nil), entry.Logger.Hooks...)
entry.Logger.mu.Unlock()

Copy link
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

it may lead to more reallocation and copy depending on the array size though.

Copy link
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

or not

Copy link
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🤷‍♂️


err := tmpHooks.Fire(entry.Level, entry)
if err != nil {
fmt.Fprintf(os.Stderr, "Failed to fire hook: %v\n", err)
}
Expand Down
16 changes: 16 additions & 0 deletions hook_test.go
Expand Up @@ -3,13 +3,15 @@ package logrus_test
import (
"bytes"
"encoding/json"
"fmt"
"sync"
"testing"

"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"

. "github.com/sirupsen/logrus"
"github.com/sirupsen/logrus/hooks/test"
. "github.com/sirupsen/logrus/internal/testutils"
)

Expand Down Expand Up @@ -191,6 +193,20 @@ func TestAddHookRace(t *testing.T) {
})
}

func TestAddHookRace2(t *testing.T) {
t.Parallel()

for i := 0; i < 3; i++ {
testname := fmt.Sprintf("Test %d", i)
t.Run(testname, func(t *testing.T) {
t.Parallel()

_ = test.NewGlobal()
Info(testname)
})
}
}

type HookCallFunc struct {
F func()
}
Expand Down