10 // FieldMap allows customization of the key names for default fields.
11 type FieldMap map[fieldKey]string
13 // Default key names for the default fields
16 FieldKeyLevel = "level"
20 func (f FieldMap) resolve(key fieldKey) string {
21 if k, ok := f[key]; ok {
28 // JSONFormatter formats logs into parsable json
29 type JSONFormatter struct {
30 // TimestampFormat sets the format used for marshaling timestamps.
31 TimestampFormat string
33 // DisableTimestamp allows disabling automatic timestamps in output
36 // FieldMap allows users to customize the names of keys for default fields.
38 // formatter := &JSONFormatter{
39 // FieldMap: FieldMap{
40 // FieldKeyTime: "@timestamp",
41 // FieldKeyLevel: "@level",
42 // FieldKeyMsg: "@message",
48 // Format renders a single log entry
49 func (f *JSONFormatter) Format(entry *Entry) ([]byte, error) {
50 data := make(Fields, len(entry.Data)+3)
51 for k, v := range entry.Data {
52 switch v := v.(type) {
54 // Otherwise errors are ignored by `encoding/json`
55 // https://github.com/sirupsen/logrus/issues/137
61 prefixFieldClashes(data)
63 timestampFormat := f.TimestampFormat
64 if timestampFormat == "" {
65 timestampFormat = defaultTimestampFormat
68 if !f.DisableTimestamp {
69 data[f.FieldMap.resolve(FieldKeyTime)] = entry.Time.Format(timestampFormat)
71 data[f.FieldMap.resolve(FieldKeyMsg)] = entry.Message
72 data[f.FieldMap.resolve(FieldKeyLevel)] = entry.Level.String()
74 serialized, err := json.Marshal(data)
76 return nil, fmt.Errorf("Failed to marshal fields to JSON, %v", err)
78 return append(serialized, '\n'), nil