From 03bdfb2ee3ff0156475620bde33be14c1a3af53f Mon Sep 17 00:00:00 2001 From: Craig Pastro Date: Wed, 5 Oct 2022 18:11:11 -0700 Subject: [PATCH] watch for multiple errors --- sugar.go | 9 ++++++++- sugar_test.go | 15 +++++++++++++++ 2 files changed, 23 insertions(+), 1 deletion(-) diff --git a/sugar.go b/sugar.go index 7eae8ffb7..61076c985 100644 --- a/sugar.go +++ b/sugar.go @@ -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 @@ -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. @@ -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 } diff --git a/sugar_test.go b/sugar_test.go index 6fdef38ca..d4daf665e 100644 --- a/sugar_test.go +++ b/sugar_test.go @@ -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 @@ -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 {