Skip to content

Commit

Permalink
Merge pull request #14 from ownersroom/fix/mutex-unlocking
Browse files Browse the repository at this point in the history
Fix panic due to missing mutex lock/unlock
  • Loading branch information
JeanMertz authored Nov 22, 2018
2 parents 5d84653 + c138d57 commit 63327ce
Show file tree
Hide file tree
Showing 3 changed files with 35 additions and 1 deletion.
2 changes: 1 addition & 1 deletion core.go
Original file line number Diff line number Diff line change
Expand Up @@ -82,7 +82,7 @@ func (c *core) Write(ent zapcore.Entry, fields []zapcore.Field) error {
fields = append(fields, labelsField(c.allLabels()))
fields = c.withSourceLocation(ent, fields)

c.tempLabels = newLabels()
c.tempLabels.reset()

return c.Core.Write(ent, fields)
}
Expand Down
28 changes: 28 additions & 0 deletions core_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ package zapdriver

import (
"runtime"
"sync/atomic"
"testing"

"github.com/stretchr/testify/require"
Expand Down Expand Up @@ -110,6 +111,33 @@ func TestWrite(t *testing.T) {
assert.NotNil(t, logs.All()[0].ContextMap()["labels"])
}

func TestWriteConcurrent(t *testing.T) {
temp := newLabels()
temp.store = map[string]string{"one": "1", "two": "2"}
goRoutines := 8
counter := int32(10000)

debugcore, logs := observer.New(zapcore.DebugLevel)
core := &core{debugcore, newLabels(), temp}

fields := []zap.Field{
zap.String("hello", "world"),
Label("one", "value"),
Label("two", "value"),
}

for i := 0; i < goRoutines; i++ {
go func() {
for atomic.AddInt32(&counter, -1) > 0 {
err := core.Write(zapcore.Entry{}, fields)
require.NoError(t, err)
}
}()
}

assert.NotNil(t, logs.All()[0].ContextMap()["labels"])
}

func TestWithAndWrite(t *testing.T) {
debugcore, logs := observer.New(zapcore.DebugLevel)
core := zapcore.Core(&core{debugcore, newLabels(), newLabels()})
Expand Down
6 changes: 6 additions & 0 deletions label.go
Original file line number Diff line number Diff line change
Expand Up @@ -58,6 +58,12 @@ func (l *labels) Add(key, value string) {
l.mutex.Unlock()
}

func (l *labels) reset() {
l.mutex.Lock()
l.store = map[string]string{}
l.mutex.Unlock()
}

func (l labels) MarshalLogObject(enc zapcore.ObjectEncoder) error {
l.mutex.RLock()
for k, v := range l.store {
Expand Down

0 comments on commit 63327ce

Please sign in to comment.