Skip to content

Commit

Permalink
fix: log.With() race condition (#64)
Browse files Browse the repository at this point in the history
* fix log.With() race condition

- added small unittest to highlight the problem
- only visible when running with -race option

* rollback fix

* fix race condition
  • Loading branch information
alexvelea authored Jul 13, 2023
1 parent 31d2a53 commit e0ec0b1
Show file tree
Hide file tree
Showing 2 changed files with 34 additions and 0 deletions.
2 changes: 2 additions & 0 deletions logger.go
Original file line number Diff line number Diff line change
Expand Up @@ -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{}
Expand Down
32 changes: 32 additions & 0 deletions logger_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ package log

import (
"bytes"
"sync"
"testing"

"github.com/stretchr/testify/assert"
Expand Down Expand Up @@ -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()
})
}
}

0 comments on commit e0ec0b1

Please sign in to comment.