9 type FieldMap map[fieldKey]string
13 FieldKeyLevel = "level"
17 func (f FieldMap) resolve(key fieldKey) string {
18 if k, ok := f[key]; ok {
25 type JSONFormatter struct {
26 // TimestampFormat sets the format used for marshaling timestamps.
27 TimestampFormat string
29 // DisableTimestamp allows disabling automatic timestamps in output
32 // FieldMap allows users to customize the names of keys for various fields.
34 // formatter := &JSONFormatter{
35 // FieldMap: FieldMap{
36 // FieldKeyTime: "@timestamp",
37 // FieldKeyLevel: "@level",
38 // FieldKeyLevel: "@message",
44 func (f *JSONFormatter) Format(entry *Entry) ([]byte, error) {
45 data := make(Fields, len(entry.Data)+3)
46 for k, v := range entry.Data {
47 switch v := v.(type) {
49 // Otherwise errors are ignored by `encoding/json`
50 // https://github.com/Sirupsen/logrus/issues/137
56 prefixFieldClashes(data)
58 timestampFormat := f.TimestampFormat
59 if timestampFormat == "" {
60 timestampFormat = DefaultTimestampFormat
63 if !f.DisableTimestamp {
64 data[f.FieldMap.resolve(FieldKeyTime)] = entry.Time.Format(timestampFormat)
66 data[f.FieldMap.resolve(FieldKeyMsg)] = entry.Message
67 data[f.FieldMap.resolve(FieldKeyLevel)] = entry.Level.String()
69 serialized, err := json.Marshal(data)
71 return nil, fmt.Errorf("Failed to marshal fields to JSON, %v", err)
73 return append(serialized, '\n'), nil