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 for SetFormatter and SetReportCaller #1263

Merged
merged 1 commit into from Jan 12, 2022
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
4 changes: 2 additions & 2 deletions entry.go
Expand Up @@ -284,13 +284,13 @@ func (entry *Entry) fireHooks() {
}

func (entry *Entry) write() {
entry.Logger.mu.Lock()
defer entry.Logger.mu.Unlock()
serialized, err := entry.Logger.Formatter.Format(entry)
if err != nil {
fmt.Fprintf(os.Stderr, "Failed to obtain reader, %v\n", err)
return
}
entry.Logger.mu.Lock()
defer entry.Logger.mu.Unlock()
if _, err := entry.Logger.Out.Write(serialized); err != nil {
fmt.Fprintf(os.Stderr, "Failed to write to log, %v\n", err)
}
Expand Down
23 changes: 23 additions & 0 deletions entry_test.go
Expand Up @@ -269,10 +269,33 @@ func TestEntryLogfLevel(t *testing.T) {
func TestEntryReportCallerRace(t *testing.T) {
logger := New()
entry := NewEntry(logger)

// logging before SetReportCaller has the highest chance of causing a race condition
// to be detected, but doing it twice just to increase the likelyhood of detecting the race
go func() {
entry.Info("should not race")
}()
go func() {
logger.SetReportCaller(true)
}()
go func() {
entry.Info("should not race")
}()
}

func TestEntryFormatterRace(t *testing.T) {
logger := New()
entry := NewEntry(logger)

// logging before SetReportCaller has the highest chance of causing a race condition
// to be detected, but doing it twice just to increase the likelyhood of detecting the race
go func() {
entry.Info("should not race")
}()
go func() {
logger.SetFormatter(&TextFormatter{})
}()
go func() {
entry.Info("should not race")
}()
}