OSDN Git Service

versoin1.1.9 (#594)
[bytom/vapor.git] / vendor / github.com / sirupsen / logrus / json_formatter.go
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         // FieldMap allows users to customize the names of keys for default fields.
37         // As an example:
38         // formatter := &JSONFormatter{
39         //      FieldMap: FieldMap{
40         //               FieldKeyTime: "@timestamp",
41         //               FieldKeyLevel: "@level",
42         //               FieldKeyMsg: "@message",
43         //    },
44         // }
45         FieldMap FieldMap
46 }
47
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) {
53                 case error:
54                         // Otherwise errors are ignored by `encoding/json`
55                         // https://github.com/sirupsen/logrus/issues/137
56                         data[k] = v.Error()
57                 default:
58                         data[k] = v
59                 }
60         }
61         prefixFieldClashes(data)
62
63         timestampFormat := f.TimestampFormat
64         if timestampFormat == "" {
65                 timestampFormat = defaultTimestampFormat
66         }
67
68         if !f.DisableTimestamp {
69                 data[f.FieldMap.resolve(FieldKeyTime)] = entry.Time.Format(timestampFormat)
70         }
71         data[f.FieldMap.resolve(FieldKeyMsg)] = entry.Message
72         data[f.FieldMap.resolve(FieldKeyLevel)] = entry.Level.String()
73
74         serialized, err := json.Marshal(data)
75         if err != nil {
76                 return nil, fmt.Errorf("Failed to marshal fields to JSON, %v", err)
77         }
78         return append(serialized, '\n'), nil
79 }