2015-01-12 21:33:08 +00:00
|
|
|
package logrus
|
|
|
|
|
|
|
|
import (
|
|
|
|
"encoding/json"
|
|
|
|
"fmt"
|
|
|
|
)
|
|
|
|
|
2015-04-10 20:54:53 +00:00
|
|
|
type JSONFormatter struct {
|
|
|
|
// TimestampFormat sets the format used for marshaling timestamps.
|
|
|
|
TimestampFormat string
|
|
|
|
}
|
2015-01-12 21:33:08 +00:00
|
|
|
|
|
|
|
func (f *JSONFormatter) Format(entry *Entry) ([]byte, error) {
|
2015-02-05 20:00:07 +00:00
|
|
|
data := make(Fields, len(entry.Data)+3)
|
|
|
|
for k, v := range entry.Data {
|
2015-03-24 03:09:19 +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-02-05 20:00:07 +00:00
|
|
|
}
|
|
|
|
prefixFieldClashes(data)
|
2015-04-10 20:54:53 +00:00
|
|
|
|
|
|
|
if f.TimestampFormat == "" {
|
|
|
|
f.TimestampFormat = DefaultTimestampFormat
|
|
|
|
}
|
|
|
|
|
|
|
|
data["time"] = entry.Time.Format(f.TimestampFormat)
|
2015-02-05 20:00:07 +00:00
|
|
|
data["msg"] = entry.Message
|
|
|
|
data["level"] = entry.Level.String()
|
2015-01-12 21:33:08 +00:00
|
|
|
|
2015-02-05 20:00:07 +00:00
|
|
|
serialized, err := json.Marshal(data)
|
2015-01-12 21:33:08 +00:00
|
|
|
if err != nil {
|
|
|
|
return nil, fmt.Errorf("Failed to marshal fields to JSON, %v", err)
|
|
|
|
}
|
|
|
|
return append(serialized, '\n'), nil
|
|
|
|
}
|