woodpecker/vendor/github.com/Sirupsen/logrus/json_formatter.go

42 lines
940 B
Go
Raw Normal View History

2015-05-22 18:37:40 +00:00
package logrus
import (
"encoding/json"
"fmt"
)
2016-04-11 22:55:13 +00:00
type JSONFormatter struct {
// TimestampFormat sets the format used for marshaling timestamps.
TimestampFormat string
}
2015-05-22 18:37:40 +00:00
func (f *JSONFormatter) Format(entry *Entry) ([]byte, error) {
data := make(Fields, len(entry.Data)+3)
for k, v := range entry.Data {
2016-04-11 22:55:13 +00:00
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
}
2015-05-22 18:37:40 +00:00
}
prefixFieldClashes(data)
2016-04-11 22:55:13 +00:00
timestampFormat := f.TimestampFormat
if timestampFormat == "" {
timestampFormat = DefaultTimestampFormat
}
data["time"] = entry.Time.Format(timestampFormat)
2015-05-22 18:37:40 +00:00
data["msg"] = entry.Message
data["level"] = entry.Level.String()
serialized, err := json.Marshal(data)
if err != nil {
return nil, fmt.Errorf("Failed to marshal fields to JSON, %v", err)
}
return append(serialized, '\n'), nil
}