Skip to content

Commit

Permalink
Fix sugar logger key/value conversions (#30)
Browse files Browse the repository at this point in the history
- fixes a bug where a single item in an array of key/value pairs failed with an IndexOutOfRange.
  • Loading branch information
wiggin77 authored Sep 10, 2021
1 parent 51a79cd commit b04a614
Show file tree
Hide file tree
Showing 2 changed files with 48 additions and 0 deletions.
1 change: 1 addition & 0 deletions sugar.go
Original file line number Diff line number Diff line change
Expand Up @@ -182,6 +182,7 @@ func (s Sugar) argsToFields(keyValuePairs []interface{}) []Field {

if i == count-1 {
s.logger.Error("invalid key/value pair", Any("arg", keyValuePairs[i]))
break
}

// we should have a key/value pair now. The key must be a string.
Expand Down
47 changes: 47 additions & 0 deletions sugar_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ package logr_test

import (
"bytes"
"strings"
"testing"

"github.com/mattermost/logr/v2"
Expand Down Expand Up @@ -74,6 +75,52 @@ func TestSugarLogger(t *testing.T) {
assert.Contains(t, data, "prop4=bar")
}

type kv []interface{}

const (
pre = "debug | test msg | test=sugar "
errInvalidKey = "error | invalid key"
)

func TestSugar_argsToFields(t *testing.T) {
tests := []struct {
name string
keyValuePairs kv
want string
wantErr bool
}{
{name: "one pair", keyValuePairs: kv{"prop1", 7}, want: pre + "prop1=7"},
{name: "two pair", keyValuePairs: kv{"prop1", 11, "prop2", "bar"}, want: pre + "prop1=11 prop2=bar"},
{name: "empty", keyValuePairs: kv{}, want: pre},
{name: "invalid key", keyValuePairs: kv{200, 300}, wantErr: true},
{name: "one arg", keyValuePairs: kv{"bad"}, wantErr: true},
{name: "one arg invalid", keyValuePairs: kv{22}, wantErr: true},
{name: "nil args", keyValuePairs: nil, want: pre},
{name: "dangling key", keyValuePairs: kv{"prop1", 7, "dangle"}, wantErr: true},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
buf := &bytes.Buffer{}
sugar, shutdown, err := makeSugar(buf)
require.NoError(t, err)

sugar.Debugw("test msg", tt.keyValuePairs...)

err = shutdown()
require.NoError(t, err)

got := strings.TrimSpace(buf.String())
want := strings.TrimSpace(tt.want)

if tt.wantErr {
assert.Contains(t, got, errInvalidKey)
} else {
assert.Equal(t, want, got)
}
})
}
}

func makeSugar(buf *bytes.Buffer) (logr.Sugar, func() error, error) {
formatter := &formatters.Plain{DisableTimestamp: true, Delim: " | "}
filter := &logr.StdFilter{Lvl: logr.Debug, Stacktrace: logr.Error}
Expand Down

0 comments on commit b04a614

Please sign in to comment.