Skip to content

Commit

Permalink
Store verbose error under a separate key
Browse files Browse the repository at this point in the history
  • Loading branch information
Akshay Shah committed Feb 20, 2017
1 parent bd30b7e commit 023612a
Show file tree
Hide file tree
Showing 3 changed files with 12 additions and 4 deletions.
4 changes: 4 additions & 0 deletions field.go
Original file line number Diff line number Diff line change
Expand Up @@ -175,6 +175,10 @@ func Time(key string, val time.Time) zapcore.Field {
// "error". If passed a nil error, the field is a no-op. This is purely a
// convenience for a common error-logging idiom; use String("someFieldName",
// err.Error()) to customize the key.
//
// Errors which also implement fmt.Formatter (like those produced by
// github.com/pkg/errors) will also have their verbose representation stored
// under "errorVerbose".
func Error(err error) zapcore.Field {
if err == nil {
return Skip()
Expand Down
5 changes: 2 additions & 3 deletions zapcore/field.go
Original file line number Diff line number Diff line change
Expand Up @@ -155,10 +155,9 @@ func (f Field) AddTo(enc ObjectEncoder) {
if fancy, ok := val.(fmt.Formatter); ok {
// This is a rich error type, like those produced by
// github.com/pkg/errors.
enc.AddString(f.Key, fmt.Sprintf("%+v", fancy))
} else {
enc.AddString(f.Key, val.Error())
enc.AddString(f.Key+"Verbose", fmt.Sprintf("%+v", fancy))
}
enc.AddString(f.Key, val.Error())
case SkipType:
break
default:
Expand Down
7 changes: 6 additions & 1 deletion zapcore/field_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -126,6 +126,9 @@ func TestFields(t *testing.T) {
f := Field{Key: "k", Type: tt.t, Integer: tt.i, Interface: tt.iface, String: tt.s}
f.AddTo(enc)
assert.Equal(t, tt.want, enc.Fields["k"], "Unexpected output from field %+v.", f)

delete(enc.Fields, "k")
assert.Equal(t, 0, len(enc.Fields), "Unexpected extra fields present.")
}
}

Expand All @@ -137,7 +140,9 @@ func TestRichErrorSupport(t *testing.T) {
}
enc := NewMapObjectEncoder()
f.AddTo(enc)
serialized := enc.Fields["k"]
assert.Equal(t, "failed: egad", enc.Fields["k"], "Unexpected basic error message.")

serialized := enc.Fields["kVerbose"]
// Don't assert the exact format used by a third-party package, but ensure
// that some critical elements are present.
assert.Regexp(t, `egad`, serialized, "Expected original error message to be present.")
Expand Down

0 comments on commit 023612a

Please sign in to comment.