From 78f838918da24e1487e8341227d48cc80bb73966 Mon Sep 17 00:00:00 2001 From: Ruben de Vries Date: Wed, 16 Jun 2021 11:54:39 +0200 Subject: [PATCH] fix race condition for SetFormatter and properly fix SetReportCaller race as well --- entry.go | 4 ++-- entry_test.go | 23 +++++++++++++++++++++++ 2 files changed, 25 insertions(+), 2 deletions(-) diff --git a/entry.go b/entry.go index 0a5a832..ad9957b 100644 --- a/entry.go +++ b/entry.go @@ -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) } diff --git a/entry_test.go b/entry_test.go index 035e411..41c47a2 100644 --- a/entry_test.go +++ b/entry_test.go @@ -269,6 +269,12 @@ 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) }() @@ -276,3 +282,20 @@ func TestEntryReportCallerRace(t *testing.T) { 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") + }() +}