Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Support error array in field when using json formatter #1413

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
10 changes: 10 additions & 0 deletions json_formatter.go
Expand Up @@ -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)
Expand All @@ -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
}
Expand Down
32 changes: 31 additions & 1 deletion json_formatter_test.go
Expand Up @@ -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"])
}
}

Expand Down