Skip to content

Commit

Permalink
Format errors correctly
Browse files Browse the repository at this point in the history
Errors included in a logrus.Entry are not formatted correctly. This is caused
by sirupsen/logrus#137
  • Loading branch information
Tamir Sen committed Jun 23, 2018
1 parent aa17bfa commit 5e4ed8a
Show file tree
Hide file tree
Showing 2 changed files with 41 additions and 7 deletions.
18 changes: 17 additions & 1 deletion formatter.go
Original file line number Diff line number Diff line change
Expand Up @@ -129,6 +129,22 @@ func (f *Formatter) errorOrigin() (stack.Call, error) {
}
}

// taken from https://github.com/sirupsen/logrus/blob/master/json_formatter.go#L51
func replaceErrors(source logrus.Fields) logrus.Fields {
data := make(logrus.Fields, len(source))
for k, v := range source {
switch v := v.(type) {
case error:
// Otherwise errors are ignored by `encoding/json`
// https://github.com/sirupsen/logrus/issues/137
data[k] = v.Error()
default:
data[k] = v
}
}
return data
}

// Format formats a logrus entry according to the Stackdriver specifications.
func (f *Formatter) Format(e *logrus.Entry) ([]byte, error) {
severity := levelsToSeverity[e.Level]
Expand All @@ -138,7 +154,7 @@ func (f *Formatter) Format(e *logrus.Entry) ([]byte, error) {
Message: e.Message,
Severity: severity,
Context: &context{
Data: e.Data,
Data: replaceErrors(e.Data),
},
}

Expand Down
30 changes: 24 additions & 6 deletions formatter_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -54,6 +54,24 @@ var formatterTests = []struct {
},
},
},
{
run: func(logger *logrus.Logger) {
logger.
WithField("foo", "bar").
WithError(errors.New("test error")).
Info("my log entry")
},
out: map[string]interface{}{
"severity": "INFO",
"message": "my log entry",
"context": map[string]interface{}{
"data": map[string]interface{}{
"foo": "bar",
"error": "test error",
},
},
},
},
{
run: func(logger *logrus.Logger) {
logger.WithField("foo", "bar").Error("my log entry")
Expand All @@ -71,8 +89,8 @@ var formatterTests = []struct {
},
"reportLocation": map[string]interface{}{
"filePath": "github.com/TV4/logrus-stackdriver-formatter/formatter_test.go",
"lineNumber": 59.0,
"functionName": "glob..func2",
"lineNumber": 77.0,
"functionName": "glob..func3",
},
},
},
Expand All @@ -97,8 +115,8 @@ var formatterTests = []struct {
},
"reportLocation": map[string]interface{}{
"filePath": "github.com/TV4/logrus-stackdriver-formatter/formatter_test.go",
"lineNumber": 85.0,
"functionName": "glob..func3",
"lineNumber": 103.0,
"functionName": "glob..func4",
},
},
},
Expand Down Expand Up @@ -130,8 +148,8 @@ var formatterTests = []struct {
},
"reportLocation": map[string]interface{}{
"filePath": "github.com/TV4/logrus-stackdriver-formatter/formatter_test.go",
"lineNumber": 115.0,
"functionName": "glob..func4",
"lineNumber": 133.0,
"functionName": "glob..func5",
},
},
},
Expand Down

0 comments on commit 5e4ed8a

Please sign in to comment.