logrus/json_formatter.go

74 lines
1.7 KiB
Go
Raw Normal View History

2014-03-11 03:22:08 +04:00
package logrus
import (
"encoding/json"
"fmt"
)
type fieldKey string
type FieldMap map[fieldKey]string
const (
FieldKeyMsg = "msg"
FieldKeyLevel = "level"
FieldKeyTime = "time"
FieldKeyCaller = "method"
)
func (f FieldMap) resolve(key fieldKey) string {
if k, ok := f[key]; ok {
return k
}
return string(key)
}
type JSONFormatter struct {
// TimestampFormat sets the format used for marshaling timestamps.
TimestampFormat string
// FieldMap allows users to customize the names of keys for various fields.
// As an example:
// formatter := &JSONFormatter{
// FieldMap: FieldMap{
// FieldKeyTime: "@timestamp",
// FieldKeyLevel: "@level",
// FieldKeyMsg: "@message",
// FieldKeyCaller: "@caller",
// },
// }
FieldMap FieldMap
}
2014-03-11 03:22:08 +04:00
func (f *JSONFormatter) Format(entry *Entry) ([]byte, error) {
data := make(Fields, len(entry.Data)+4)
2014-12-10 05:53:40 +03:00
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)
2015-05-26 16:02:13 +03:00
timestampFormat := f.TimestampFormat
if timestampFormat == "" {
timestampFormat = DefaultTimestampFormat
}
data[f.FieldMap.resolve(FieldKeyTime)] = entry.Time.Format(timestampFormat)
data[f.FieldMap.resolve(FieldKeyMsg)] = entry.Message
data[f.FieldMap.resolve(FieldKeyLevel)] = entry.Level.String()
if ReportCaller() {
data[f.FieldMap.resolve(FieldKeyCaller)] = entry.Caller
}
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
}