diff --git a/json_formatter.go b/json_formatter.go index c96dc563..0913315d 100644 --- a/json_formatter.go +++ b/json_formatter.go @@ -59,6 +59,14 @@ type JSONFormatter struct { PrettyPrint bool } +func errorsArrayToStrings(errs []error) []string { + strs := make([]string, len(errs)) + for i, err := range errs { + strs[i] = err.Error() + } + return strs +} + // Format renders a single log entry func (f *JSONFormatter) Format(entry *Entry) ([]byte, error) { data := make(Fields, len(entry.Data)+4) @@ -68,6 +76,8 @@ func (f *JSONFormatter) Format(entry *Entry) ([]byte, error) { // Otherwise errors are ignored by `encoding/json` // https://github.com/sirupsen/logrus/issues/137 data[k] = v.Error() + case []error: + data[k] = errorsArrayToStrings(v) default: data[k] = v } diff --git a/json_formatter_test.go b/json_formatter_test.go index 7a48f2dc..b211e581 100644 --- a/json_formatter_test.go +++ b/json_formatter_test.go @@ -24,7 +24,37 @@ func TestErrorNotLost(t *testing.T) { } if entry["error"] != "wild walrus" { - t.Fatal("Error field not set") + t.Fatal("Error field not correct: ", entry["error"]) + } +} + +func TestErrorsNotLost(t *testing.T) { + formatter := &JSONFormatter{} + + b, err := formatter.Format( + WithField("errors", []error{ + errors.New("wild walrus"), + errors.New("mild wombat"), + }), + ) + if err != nil { + t.Fatal("Unable to format entry: ", err) + } + + entry := make(map[string]interface{}) + err = json.Unmarshal(b, &entry) + if err != nil { + t.Fatal("Unable to unmarshal formatted entry: ", err) + } + + fmt.Println(string(b)) + + errs, ok := entry["errors"].([]interface{}) + if !ok { + t.Fatalf("Errors field type not correct: %T", entry["errors"]) + } + if errs[0] != "wild walrus" || errs[1] != "mild wombat" { + t.Fatal("Error field not correct: ", entry["errors"]) } }