2014-03-10 23:22:08 +00:00
|
|
|
package logrus
|
|
|
|
|
|
|
|
import (
|
|
|
|
"encoding/json"
|
|
|
|
"fmt"
|
|
|
|
)
|
2016-11-18 19:02:11 +00:00
|
|
|
|
2016-11-17 19:28:41 +00:00
|
|
|
type fieldKey string
|
2016-11-17 23:16:46 +00:00
|
|
|
type FieldMap map[fieldKey]string
|
2016-11-17 19:28:41 +00:00
|
|
|
|
|
|
|
const (
|
2016-11-17 23:16:46 +00:00
|
|
|
FieldKeyMsg = "msg"
|
|
|
|
FieldKeyLevel = "level"
|
|
|
|
FieldKeyTime = "time"
|
2016-11-17 19:28:41 +00:00
|
|
|
)
|
|
|
|
|
2016-11-17 23:16:46 +00:00
|
|
|
func (f FieldMap) resolve(key fieldKey) string {
|
|
|
|
if k, ok := f[key]; ok {
|
|
|
|
return k
|
|
|
|
}
|
|
|
|
|
|
|
|
return string(key)
|
|
|
|
}
|
|
|
|
|
2015-04-04 00:25:25 +00:00
|
|
|
type JSONFormatter struct {
|
|
|
|
// TimestampFormat sets the format used for marshaling timestamps.
|
|
|
|
TimestampFormat string
|
2016-11-18 19:02:11 +00:00
|
|
|
|
|
|
|
// FieldMap allows users to customize the names of keys for various fields.
|
|
|
|
// As an example:
|
|
|
|
// formatter := &JSONFormatter{
|
|
|
|
// FieldMap: FieldMap{
|
|
|
|
// FieldKeyTime: "@timestamp",
|
|
|
|
// FieldKeyLevel: "@level",
|
|
|
|
// FieldKeyLevel: "@message",
|
|
|
|
// },
|
|
|
|
// }
|
|
|
|
FieldMap FieldMap
|
2015-04-04 00:25:25 +00:00
|
|
|
}
|
2014-03-10 23:22:08 +00:00
|
|
|
|
|
|
|
func (f *JSONFormatter) Format(entry *Entry) ([]byte, error) {
|
2014-12-10 02:53:40 +00:00
|
|
|
data := make(Fields, len(entry.Data)+3)
|
|
|
|
for k, v := range entry.Data {
|
2015-03-10 16:04:57 +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:
|
2015-03-09 15:15:08 +00:00
|
|
|
data[k] = v
|
|
|
|
}
|
2014-12-10 02:53:40 +00:00
|
|
|
}
|
|
|
|
prefixFieldClashes(data)
|
2015-04-04 00:25:25 +00:00
|
|
|
|
2015-05-26 13:02:13 +00:00
|
|
|
timestampFormat := f.TimestampFormat
|
|
|
|
if timestampFormat == "" {
|
|
|
|
timestampFormat = DefaultTimestampFormat
|
2015-04-04 00:25:25 +00:00
|
|
|
}
|
|
|
|
|
2016-11-17 23:16:46 +00:00
|
|
|
data[f.FieldMap.resolve(FieldKeyTime)] = entry.Time.Format(timestampFormat)
|
|
|
|
data[f.FieldMap.resolve(FieldKeyMsg)] = entry.Message
|
|
|
|
data[f.FieldMap.resolve(FieldKeyLevel)] = entry.Level.String()
|
2014-07-27 01:26:04 +00:00
|
|
|
|
2014-12-10 02:53:40 +00:00
|
|
|
serialized, err := json.Marshal(data)
|
2014-03-10 23:22:08 +00:00
|
|
|
if err != nil {
|
|
|
|
return nil, fmt.Errorf("Failed to marshal fields to JSON, %v", err)
|
|
|
|
}
|
|
|
|
return append(serialized, '\n'), nil
|
|
|
|
}
|