Skip to content

Commit

Permalink
Merge pull request #15 from iamd3vil/fix/default-fields-odd
Browse files Browse the repository at this point in the history
Fix panic in case of odd fields while default fields are not nil.
  • Loading branch information
mr-karan authored Jul 8, 2022
2 parents 3fd32be + ab5d82f commit 51f6b97
Show file tree
Hide file tree
Showing 2 changed files with 17 additions and 1 deletion.
6 changes: 5 additions & 1 deletion log.go
Original file line number Diff line number Diff line change
Expand Up @@ -87,6 +87,10 @@ func New(opts Opts) Logger {
opts.CallerSkipFrameCount = 3
}

if len(opts.DefaultFields)%2 != 0 {
opts.DefaultFields = opts.DefaultFields[0 : len(opts.DefaultFields)-1]
}

return Logger{
out: newSyncWriter(opts.Writer),
Opts: opts,
Expand Down Expand Up @@ -195,7 +199,7 @@ func (l Logger) handleLog(msg string, lvl Level, fields ...any) {

// If there are odd number of fields, ignore the last.
if fieldCount%2 != 0 {
fields = fields[0 : fieldCount-1]
fields = fields[0 : len(fields)-1]
}

for i := range l.DefaultFields {
Expand Down
12 changes: 12 additions & 0 deletions log_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -223,6 +223,18 @@ func TestOddNumberedFields(t *testing.T) {
buf.Reset()
}

func TestOddNumberedFieldsWithDefaultFields(t *testing.T) {
buf := &bytes.Buffer{}
l := New(Opts{Writer: buf, DefaultFields: []any{
"defaultkey", "defaultval",
}})

// Give a odd number of fields.
l.Info("hello world", "key1", "val1", "key2")
require.Contains(t, buf.String(), `level=info message="hello world" defaultkey=defaultval key1=val1`)
buf.Reset()
}

// These test are typically meant to be run with the data race detector.
func TestLoggerConcurrency(t *testing.T) {
buf := &bytes.Buffer{}
Expand Down

0 comments on commit 51f6b97

Please sign in to comment.