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 log.With() race condition #64

Merged
merged 3 commits into from
Jul 13, 2023
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.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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()
})
}
}