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 concurrency issue by copying map of Fields #110

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
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
10 changes: 8 additions & 2 deletions logger.go
Original file line number Diff line number Diff line change
Expand Up @@ -17,9 +17,15 @@ type Fielder interface {
// Fields represents a map of entry level data used for structured logging.
type Fields map[string]interface{}

// Fields implements Fielder.
// Fields implements Fielder, returning a shallow copy of Fields.
// This is to prevent runtime error that happens when we read and
// write a map at the same time.
func (f Fields) Fields() Fields {
return f
res := map[string]interface{}{}
for k, v := range f {
res[k] = v
}
return res
}

// Get field value by name.
Expand Down
39 changes: 39 additions & 0 deletions logger_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ package log_test

import (
"fmt"
"sync"
"testing"

"github.com/apex/log"
Expand Down Expand Up @@ -194,6 +195,44 @@ func TestLogger_HandlerFunc(t *testing.T) {
assert.Equal(t, e.Level, log.InfoLevel)
}

// TestLogger_Concurrent is testing the thread-safety of the library.
// We're running a custom attribute that is read and written at the same
// time in different goroutines.
//
// If the library is thread safe, this operation won't have any runtime errors.
func TestLogger_Concurrent(t *testing.T) {
var l log.Interface
l = &log.Logger{
Handler: discard.New(),
Level: log.DebugLevel,
}

type attribute map[string]interface{}
type withAttr struct {
guard sync.Mutex
attrs attribute
}

mm := withAttr{attrs: attribute{"one": 1}}

// loop to make sure collision of read and write happens
for i := 0; i < 50; i++ {
// write the fields
go func(val int) {
mm.guard.Lock()
defer mm.guard.Unlock()

mm.attrs[fmt.Sprintf("%d", val+1)] = val * val
l = l.WithFields(log.Fields(mm.attrs))
}(i)

// read the fields
go func(val int) {
l.Debugf("read %d", val)
}(i)
}
}

func BenchmarkLogger_small(b *testing.B) {
l := &log.Logger{
Handler: discard.New(),
Expand Down