Debian Codegraph @

vendor/github.com/sirupsen/logrus/json_formatter.go

raw
1 package logrus
2
3 import (
4 "encoding/json"
5 "fmt"
6 )
7
8 type fieldKey string
9
10 // FieldMap allows customization of the key names for default fields.
11 type FieldMap map[fieldKey]string
12
13 // Default key names for the default fields
14 const (
15 FieldKeyMsg = "msg"
16 FieldKeyLevel = "level"
17 FieldKeyTime = "time"
18 )
19
20 func (f FieldMap) resolve(key fieldKey) string {
21 if k, ok := f[key]; ok {
22 return k
23 }
24
25 return string(key)
26 }
27
28 // JSONFormatter formats logs into parsable json
29 type JSONFormatter struct {
30 // TimestampFormat sets the format used for marshaling timestamps.
31 TimestampFormat string
32
33 // DisableTimestamp allows disabling automatic timestamps in output
34 DisableTimestamp bool
35
36 // DataKey allows users to put all the log entry parameters into a nested dictionary at a given key.
37 DataKey string
38
39 // FieldMap allows users to customize the names of keys for default fields.
40 // As an example:
41 // formatter := &JSONFormatter{
42 // FieldMap: FieldMap{
43 // FieldKeyTime: "@timestamp",
44 // FieldKeyLevel: "@level",
45 // FieldKeyMsg: "@message",
46 // },
47 // }
48 FieldMap FieldMap
49 }
50
51 // Format renders a single log entry
52 func (f *JSONFormatter) Format(entry *Entry) ([]byte, error) {
53 data := make(Fields, len(entry.Data)+3)
54 for k, v := range entry.Data {
55 switch v := v.(type) {
56 case error:
57 // Otherwise errors are ignored by `encoding/json`
58 // https://github.com/sirupsen/logrus/issues/137
59 data[k] = v.Error()
60 default:
61 data[k] = v
62 }
63 }
64
65 if f.DataKey != "" {
66 newData := make(Fields, 4)
67 newData[f.DataKey] = data
68 data = newData
69 }
70
71 prefixFieldClashes(data, f.FieldMap)
72
73 timestampFormat := f.TimestampFormat
74 if timestampFormat == "" {
75 timestampFormat = defaultTimestampFormat
76 }
77
78 if !f.DisableTimestamp {
79 data[f.FieldMap.resolve(FieldKeyTime)] = entry.Time.Format(timestampFormat)
80 }
81 data[f.FieldMap.resolve(FieldKeyMsg)] = entry.Message
82 data[f.FieldMap.resolve(FieldKeyLevel)] = entry.Level.String()
83
84 serialized, err := json.Marshal(data)
85 if err != nil {
86 return nil, fmt.Errorf("Failed to marshal fields to JSON, %v", err)
87 }
88 return append(serialized, '\n'), nil
89 }