-
Notifications
You must be signed in to change notification settings - Fork 5
/
Copy pathjson_formatter.go
244 lines (217 loc) · 6.56 KB
/
json_formatter.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
package log
import (
"bytes"
"encoding/json"
"fmt"
"strings"
"sync"
"text/template"
)
var funcMap = template.FuncMap{
// The name "title" is what the function will be called in the template text.
"newCounter": func(data interface{}) map[string]int {
var max int
switch v := data.(type) {
case map[string]interface{}:
max = len(v) - 1
case []string:
max = len(v) - 1
}
return map[string]int{
"max": max,
"cnt": 0,
"comma": 1,
}
},
"inc": func(counter map[string]int) map[string]int {
counter["cnt"] = counter["cnt"] + 1
if counter["cnt"] >= counter["max"] {
counter["comma"] = 0
}
return counter
},
"json": func(v interface{}, prefix, indent string) string {
byts, err := json.MarshalIndent(v, prefix, indent)
if nil == err {
return string(byts)
}
return ""
},
}
var jsonTermTemplate = template.Must(template.New("tty").Funcs(funcMap).Parse(
"{{$color := .Color}}{{$caller := .Caller}}{\n" +
// Level
" \"{{$color.Level}}{{.LabelLevel}}{{$color.Reset}}\": \"{{$color.Level}}{{printf \"%5s\" .Level}}{{$color.Reset}}\",\n" +
// Hostname
"{{if .Hostname}}" +
" \"{{$color.Level}}{{.LabelHost}}{{$color.Reset}}\": \"{{$color.Hostname}}{{.Hostname}}{{$color.Reset}}\",\n" +
"{{end}}" +
// Timestamp
"{{if .Timestamp}}" +
" \"{{$color.Level}}{{.LabelTime}}{{$color.Reset}}\": \"{{$color.Timestamp}}{{.Timestamp}}{{$color.Reset}}\",\n" +
"{{end}}" +
// Message
" \"{{$color.Level}}{{.LabelMsg}}{{$color.Reset}}\": \"{{printf \"%s\" .Message}}\",\n" +
// Error
"{{if .Err}}" +
" \"{{$color.Level}}{{.LabelError}}{{$color.Reset}}\": {{$color.Err}}{{json .Err (printf \"%s \" $color.Err) \" \"}}{{$color.Reset}}\n" +
"{{end}}" +
// Data fields
"{{if .Data}}" +
"{{$counter := newCounter .Data}}" +
" \"{{$color.Level}}{{.LabelData}}{{$color.Reset}}\": {\n{{range $k, $v := .Data}}" +
" \"{{$color.DataLabel}}{{$k}}{{$color.Reset}}\": {{$color.DataValue}}{{json $v (printf \"%s \" $color.DataValue) \" \"}}{{$color.Reset}}{{if eq 1 $counter.comma}},{{end}}\n" +
"{{$_ := inc $counter}}" +
"{{end}} },\n" +
"{{end}}" +
// Caller
"{{if and (.Caller) (not .Trace)}}" +
" \"{{$color.Level}}{{.LabelCaller}}{{$color.Reset}}\": \"{{$color.Caller}}{{.Caller}}{{$color.Reset}}\"\n" +
"{{end}}" +
// Trace
"{{if .Trace}}" +
"{{$counter := newCounter .Trace}}" +
" \"{{$color.Level}}{{.LabelTrace}}{{$color.Reset}}\": [\n{{range $k, $v := .Trace}}" +
" \"{{$color.Trace}}{{$v}}{{$color.Reset}}\"{{if eq 1 $counter.comma}},{{end}}\n" +
"{{$_ := inc $counter}}" +
"{{end}} ]\n" +
"{{end}}" +
"}",
))
// JSONFormatter formats logs into parsable json.
type JSONFormatter struct {
// DataKey allows users to put all the log entry parameters into a
// nested dictionary at a given key.
DataKey string
// DisableCaller disables caller data output.
DisableCaller bool
// DisableHostname disables hostname output.
DisableHostname bool
// DisableLevel disables level output.
DisableLevel bool
// DisableMessage disables message output.
DisableMessage bool
// DisableTimestamp disables timestamp output.
DisableTimestamp bool
// DisableTTY disables TTY formatted output.
DisableTTY bool
// Enable full backtrace output.
EnableTrace bool
// EscapeHTML is a flag that notes whether HTML characters should be
// escaped.
EscapeHTML bool
// ForceTTY forces TTY formatted output.
ForceTTY bool
// FieldMap allows users to customize the names of keys for default
// fields.
//
// For example:
// formatter := &TextFormatter{FieldMap: FieldMap{
// LabelCaller: "@caller",
// LabelData: "@data",
// LabelHost: "@hostname",
// LabelLevel: "@loglevel",
// LabelMsg: "@message",
// LabelTime: "@timestamp",
// }}
FieldMap FieldMap
// TimestampFormat allows a custom timestamp format to be used.
TimestampFormat string
// Flag noting whether the logger's output is to a terminal
isTerminal bool
sync.Once
}
func (f *JSONFormatter) init(entry *Entry) {
if entry.Logger != nil {
f.isTerminal = checkIfTerminal(entry.Logger.Out)
}
}
// Format renders a single log entry
func (f *JSONFormatter) Format(entry *Entry) ([]byte, error) {
var err error
var serialized []byte
isTTY := (f.ForceTTY || f.isTerminal) && !f.DisableTTY
prefixFieldClashes(entry.Data, f.FieldMap)
f.Do(func() { f.init(entry) })
data := getData(entry, f.FieldMap, f.EscapeHTML, isTTY)
if f.DisableTimestamp {
data.Timestamp = ""
} else if "" != f.TimestampFormat {
data.Timestamp = entry.Time.Format(f.TimestampFormat)
} else {
data.Timestamp = entry.Time.Format(defaultTimestampFormat)
}
if f.DisableHostname {
data.Hostname = ""
}
if f.DisableCaller {
data.Caller = ""
}
if !f.EnableTrace {
data.Trace = []string{}
}
if nil != data.Err {
if _, ok := data.Err.(json.Marshaler); !ok {
if e, ok := data.Err.(error); ok {
data.Err = e.Error()
}
}
}
if isTTY {
var logLine *bytes.Buffer
if entry.Buffer != nil {
logLine = entry.Buffer
} else {
logLine = &bytes.Buffer{}
}
err = jsonTermTemplate.Execute(logLine, data)
if err != nil {
return nil, fmt.Errorf("Failed to marshal fields to JSON, %v", err)
}
serialized = logLine.Bytes()
} else {
// Relabel data for JSON output
jsonData := map[string]interface{}{}
if !f.DisableCaller || f.EnableTrace {
jsonData[f.FieldMap.resolve(LabelCaller)] = data.Caller
}
if f.EnableTrace {
jsonData[f.FieldMap.resolve(LabelTrace)] = data.Trace
}
if !f.DisableHostname {
jsonData[f.FieldMap.resolve(LabelHost)] = data.Hostname
}
if !f.DisableLevel {
jsonData[f.FieldMap.resolve(LabelLevel)] = data.Level
}
if !f.DisableMessage {
jsonData[f.FieldMap.resolve(LabelMsg)] = data.Message
}
if !f.DisableTimestamp {
if "" != f.TimestampFormat {
jsonData[f.FieldMap.resolve(LabelTime)] = entry.Time.Format(f.TimestampFormat)
} else {
jsonData[f.FieldMap.resolve(LabelTime)] = entry.Time.Format(defaultTimestampFormat)
}
}
// account for weird error conversion
for k, v := range data.Data {
if e, ok := v.(error); ok {
data.Data[k] = e.Error()
}
}
jsonData[f.FieldMap.resolve(LabelData)] = data.Data
if nil != data.Err {
jsonData[f.FieldMap.resolve(LabelError)] = data.Err
}
buf := new(bytes.Buffer)
encoder := json.NewEncoder(buf)
encoder.SetEscapeHTML(f.EscapeHTML)
err = encoder.Encode(jsonData)
serialized = []byte(strings.Trim(buf.String(), "\n"))
}
if err != nil {
return nil, fmt.Errorf("Failed to marshal fields to JSON, %v", err)
}
return append(serialized, '\n'), nil
}