mirror of https://github.com/sirupsen/logrus.git
Merge pull request #707 from imjching/logger-with-hooks-race
Fix race condition in entry fireHooks() method
This commit is contained in:
commit
8c0189d9f6
6
entry.go
6
entry.go
|
@ -113,10 +113,12 @@ func (entry Entry) log(level Level, msg string) {
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
func (entry *Entry) fireHooks() {
|
// This function is not declared with a pointer value because otherwise
|
||||||
|
// race conditions will occur when using multiple goroutines
|
||||||
|
func (entry Entry) fireHooks() {
|
||||||
entry.Logger.mu.Lock()
|
entry.Logger.mu.Lock()
|
||||||
defer entry.Logger.mu.Unlock()
|
defer entry.Logger.mu.Unlock()
|
||||||
err := entry.Logger.Hooks.Fire(entry.Level, entry)
|
err := entry.Logger.Hooks.Fire(entry.Level, &entry)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
fmt.Fprintf(os.Stderr, "Failed to fire hook: %v\n", err)
|
fmt.Fprintf(os.Stderr, "Failed to fire hook: %v\n", err)
|
||||||
}
|
}
|
||||||
|
|
|
@ -1,6 +1,7 @@
|
||||||
package test
|
package test
|
||||||
|
|
||||||
import (
|
import (
|
||||||
|
"sync"
|
||||||
"testing"
|
"testing"
|
||||||
|
|
||||||
"github.com/sirupsen/logrus"
|
"github.com/sirupsen/logrus"
|
||||||
|
@ -8,7 +9,6 @@ import (
|
||||||
)
|
)
|
||||||
|
|
||||||
func TestAllHooks(t *testing.T) {
|
func TestAllHooks(t *testing.T) {
|
||||||
|
|
||||||
assert := assert.New(t)
|
assert := assert.New(t)
|
||||||
|
|
||||||
logger, hook := NewNullLogger()
|
logger, hook := NewNullLogger()
|
||||||
|
@ -35,5 +35,27 @@ func TestAllHooks(t *testing.T) {
|
||||||
assert.Equal(logrus.ErrorLevel, hook.LastEntry().Level)
|
assert.Equal(logrus.ErrorLevel, hook.LastEntry().Level)
|
||||||
assert.Equal("Hello error", hook.LastEntry().Message)
|
assert.Equal("Hello error", hook.LastEntry().Message)
|
||||||
assert.Equal(1, len(hook.Entries))
|
assert.Equal(1, len(hook.Entries))
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestLoggingWithHooksRace(t *testing.T) {
|
||||||
|
assert := assert.New(t)
|
||||||
|
logger, hook := NewNullLogger()
|
||||||
|
|
||||||
|
var wg sync.WaitGroup
|
||||||
|
wg.Add(100)
|
||||||
|
|
||||||
|
for i := 0; i < 100; i++ {
|
||||||
|
go func() {
|
||||||
|
logger.Info("info")
|
||||||
|
wg.Done()
|
||||||
|
}()
|
||||||
|
}
|
||||||
|
|
||||||
|
assert.Equal(logrus.InfoLevel, hook.LastEntry().Level)
|
||||||
|
assert.Equal("info", hook.LastEntry().Message)
|
||||||
|
|
||||||
|
wg.Wait()
|
||||||
|
|
||||||
|
entries := hook.AllEntries()
|
||||||
|
assert.Equal(100, len(entries))
|
||||||
}
|
}
|
||||||
|
|
Loading…
Reference in New Issue