diff --git a/logger.go b/logger.go index f49d85d..cbf591f 100644 --- a/logger.go +++ b/logger.go @@ -285,7 +285,9 @@ func (l *Logger) SetCallerOffset(offset int) { // With returns a new logger with the given keyvals added. func (l *Logger) With(keyvals ...interface{}) *Logger { + l.mu.Lock() sl := *l + l.mu.Unlock() sl.b = bytes.Buffer{} sl.mu = &sync.RWMutex{} sl.helpers = &sync.Map{} diff --git a/logger_test.go b/logger_test.go index 67b831d..715fc5d 100644 --- a/logger_test.go +++ b/logger_test.go @@ -2,6 +2,7 @@ package log import ( "bytes" + "sync" "testing" "github.com/stretchr/testify/assert" @@ -151,3 +152,34 @@ func TestLogWithPrefix(t *testing.T) { }) } } + +func TestLogWithRaceCondition(t *testing.T) { + var buf bytes.Buffer + cases := []struct { + name string + }{ + { + name: "must be run with -race", + }, + } + for _, c := range cases { + t.Run(c.name, func(t *testing.T) { + buf.Reset() + l := New(&buf) + + var done sync.WaitGroup + done.Add(2) + + go func() { + l.With("arg1", "val1", "arg2", "val2") + done.Done() + }() + + go func() { + l.Info("kinda long log message") + done.Done() + }() + done.Wait() + }) + } +}