logrus/json_formatter.go

34 lines
737 B
Go
Raw Normal View History

2014-03-11 03:22:08 +04:00
package logrus
import (
"encoding/json"
"fmt"
"time"
2014-03-11 03:22:08 +04:00
)
type JSONFormatter struct{}
2014-03-11 03:22:08 +04:00
func (f *JSONFormatter) Format(entry *Entry) ([]byte, error) {
2014-12-10 05:53:40 +03:00
data := make(Fields, len(entry.Data)+3)
for k, v := range entry.Data {
2015-03-10 19:04:57 +03: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
}
2014-12-10 05:53:40 +03:00
}
prefixFieldClashes(data)
data["time"] = entry.Time.Format(time.RFC3339)
data["msg"] = entry.Message
data["level"] = entry.Level.String()
2014-12-10 05:53:40 +03:00
serialized, err := json.Marshal(data)
2014-03-11 03:22:08 +04:00
if err != nil {
return nil, fmt.Errorf("Failed to marshal fields to JSON, %v", err)
}
return append(serialized, '\n'), nil
}