Skip to content

Commit

Permalink
watch for multiple errors
Browse files Browse the repository at this point in the history
  • Loading branch information
Craig Pastro committed Oct 6, 2022
1 parent 3d92058 commit 03bdfb2
Show file tree
Hide file tree
Showing 2 changed files with 23 additions and 1 deletion.
9 changes: 8 additions & 1 deletion sugar.go
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,7 @@ import (
const (
_oddNumberErrMsg = "Ignored key without a value."
_nonStringKeyErrMsg = "Ignored key-value pairs with non-string keys."
_multipleErrMsg = "Multiple errors without a key."
)

// A SugaredLogger wraps the base Logger functionality in a slower, but less
Expand Down Expand Up @@ -340,6 +341,7 @@ func (s *SugaredLogger) sweetenFields(args []interface{}) []Field {
// fields, we shouldn't penalize them with extra allocations.
fields := make([]Field, 0, len(args))
var invalid invalidPairs
var seenError bool

for i := 0; i < len(args); {
// This is a strongly-typed field. Consume it and move on.
Expand All @@ -351,7 +353,12 @@ func (s *SugaredLogger) sweetenFields(args []interface{}) []Field {

// If it is an error, consume it and move on.
if err, ok := args[i].(error); ok {
fields = append(fields, Error(err))
if !seenError {
seenError = true
fields = append(fields, Error(err))
} else {
s.base.Error(_multipleErrMsg, Error(err))
}
i++
continue
}
Expand Down
15 changes: 15 additions & 0 deletions sugar_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -47,6 +47,12 @@ func TestSugarWith(t *testing.T) {
Context: []Field{Array("invalid", invalidPairs(pairs))},
}
}
ignoredError := func(err error) observer.LoggedEntry {
return observer.LoggedEntry{
Entry: zapcore.Entry{Level: ErrorLevel, Message: _multipleErrMsg},
Context: []Field{Error(err)},
}
}

tests := []struct {
desc string
Expand Down Expand Up @@ -123,6 +129,15 @@ func TestSugarWith(t *testing.T) {
nonString(invalidPair{2, true, "bar"}, invalidPair{5, 42, "reversed"}),
},
},
{
desc: "multiple errors",
args: []interface{}{errors.New("first"), errors.New("second"), errors.New("third")},
expected: []Field{Error(errors.New("first"))},
errLogs: []observer.LoggedEntry{
ignoredError(errors.New("second")),
ignoredError(errors.New("third")),
},
},
}

for _, tt := range tests {
Expand Down

0 comments on commit 03bdfb2

Please sign in to comment.