logrus/json_formatter.go

87 lines
1.9 KiB
Go
Raw Normal View History

2014-03-11 03:22:08 +04:00
package logrus
import (
"bytes"
2014-03-11 03:22:08 +04:00
"encoding/json"
"fmt"
)
type fieldKey string
2017-07-26 15:26:30 +03:00
// FieldMap allows customization of the key names for default fields.
type FieldMap map[fieldKey]string
2017-07-26 15:26:30 +03:00
// Default key names for the default fields
const (
FieldKeyMsg = "msg"
FieldKeyLevel = "level"
FieldKeyTime = "time"
)
func (f FieldMap) resolve(key fieldKey) string {
if k, ok := f[key]; ok {
return k
}
return string(key)
}
2017-07-26 15:26:30 +03:00
// JSONFormatter formats logs into parsable json
type JSONFormatter struct {
// TimestampFormat sets the format used for marshaling timestamps.
TimestampFormat string
// DisableTimestamp allows disabling automatic timestamps in output
DisableTimestamp bool
2017-07-26 15:26:30 +03:00
// FieldMap allows users to customize the names of keys for default fields.
// As an example:
// formatter := &JSONFormatter{
// FieldMap: FieldMap{
// FieldKeyTime: "@timestamp",
// FieldKeyLevel: "@level",
2017-05-05 15:18:10 +03:00
// FieldKeyMsg: "@message",
// },
// }
FieldMap FieldMap
}
2014-03-11 03:22:08 +04:00
2017-07-26 15:26:30 +03:00
// Format renders a single log entry
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
2015-03-10 19:04:57 +03:00
data[k] = v.Error()
default:
data[k] = v
}
2014-12-10 05:53:40 +03:00
}
prefixFieldClashes(data, f.FieldMap)
2015-05-26 16:02:13 +03:00
timestampFormat := f.TimestampFormat
if timestampFormat == "" {
2017-07-26 15:26:30 +03:00
timestampFormat = defaultTimestampFormat
}
if !f.DisableTimestamp {
data[f.FieldMap.resolve(FieldKeyTime)] = entry.Time.Format(timestampFormat)
}
data[f.FieldMap.resolve(FieldKeyMsg)] = entry.Message
data[f.FieldMap.resolve(FieldKeyLevel)] = entry.Level.String()
var b *bytes.Buffer
if entry.Buffer != nil {
b = entry.Buffer
} else {
b = &bytes.Buffer{}
}
err := json.NewEncoder(b).Encode(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 b.Bytes(), nil
2014-03-11 03:22:08 +04:00
}