-
Notifications
You must be signed in to change notification settings - Fork 1
/
formatwriter_json.go
255 lines (225 loc) · 5.09 KB
/
formatwriter_json.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
245
246
247
248
249
250
251
252
253
254
255
package mlog
import (
"fmt"
"runtime"
"time"
"unicode/utf8"
)
const hex = "0123456789abcdef"
// FormatWriterJSON writes a json structured log line.
// Example:
//
// {"time": "2016-04-29T20:49:12Z", "level": "I", "msg": "this is a log"}
type FormatWriterJSON struct{}
// Emit constructs and formats a json log line (with optional extra Attrs), then writes it to logger
func (j *FormatWriterJSON) EmitAttrs(logger *Logger, level int, message string, extra ...*Attr) {
sb := bufPool.Get()
defer bufPool.Put(sb)
flags := logger.Flags()
sb.WriteByte('{')
// if time is being logged, handle time as soon as possible
if flags&(Ltimestamp|Ltai64n) != 0 {
t := time.Now()
sb.WriteString(`"time": "`)
if flags&Ltai64n != 0 {
writeTimeTAI64N(sb, &t, flags)
} else {
writeTime(sb, &t, flags)
}
sb.WriteString(`", `)
}
if flags&Llevel != 0 {
sb.WriteString(`"level": "`)
switch level {
case -1:
sb.WriteByte('D')
case 1:
sb.WriteByte('F')
default:
sb.WriteByte('I')
}
sb.WriteString(`", `)
}
if flags&(Lshortfile|Llongfile) != 0 {
_, file, line, ok := runtime.Caller(3)
if !ok {
file = "???"
line = 0
}
if flags&Lshortfile != 0 {
short := file
for i := len(file) - 1; i > 0; i-- {
if file[i] == '/' {
short = file[i+1:]
break
}
}
file = short
}
sb.WriteString(`"caller": "`)
sb.WriteString(file)
sb.WriteByte(':')
sb.AppendIntWidth(line, 0)
sb.WriteString(`", `)
}
sb.WriteString(`"msg": "`)
encodeStringJSON(sb, message)
sb.WriteByte('"')
if len(extra) > 0 {
attrs := filterAttrs(extra)
if len(attrs) > 0 {
sb.WriteString(`, "extra": `)
encodeLogAttrsJSON(sb, attrs)
}
}
sb.WriteByte('}')
sb.WriteByte('\n')
sb.WriteTo(logger)
}
// Emit constructs and formats a json log line (with nillable extra Map), then writes it to logger
func (j *FormatWriterJSON) Emit(logger *Logger, level int, message string, extra Map) {
sb := bufPool.Get()
defer bufPool.Put(sb)
flags := logger.Flags()
sb.WriteByte('{')
// if time is being logged, handle time as soon as possible
if flags&(Ltimestamp|Ltai64n) != 0 {
t := time.Now()
sb.WriteString(`"time": "`)
if flags&Ltai64n != 0 {
writeTimeTAI64N(sb, &t, flags)
} else {
writeTime(sb, &t, flags)
}
sb.WriteString(`", `)
}
if flags&Llevel != 0 {
sb.WriteString(`"level": "`)
switch level {
case -1:
sb.WriteByte('D')
case 1:
sb.WriteByte('F')
default:
sb.WriteByte('I')
}
sb.WriteString(`", `)
}
if flags&(Lshortfile|Llongfile) != 0 {
_, file, line, ok := runtime.Caller(3)
if !ok {
file = "???"
line = 0
}
if flags&Lshortfile != 0 {
short := file
for i := len(file) - 1; i > 0; i-- {
if file[i] == '/' {
short = file[i+1:]
break
}
}
file = short
}
sb.WriteString(`"caller": "`)
sb.WriteString(file)
sb.WriteByte(':')
sb.AppendIntWidth(line, 0)
sb.WriteString(`", `)
}
sb.WriteString(`"msg": "`)
encodeStringJSON(sb, message)
sb.WriteByte('"')
if len(extra) > 0 {
sb.WriteString(`, "extra": `)
encodeLogMapJSON(sb, extra)
}
sb.WriteByte('}')
sb.WriteByte('\n')
sb.WriteTo(logger)
}
func encodeLogMapJSON(w byteSliceWriter, m Map) {
first := true
w.WriteByte('{')
for k, v := range m {
if first {
first = false
} else {
w.WriteString(`, `)
}
w.WriteByte('"')
encodeStringJSON(w, k)
w.WriteString(`": "`)
encodeStringJSON(w, fmt.Sprint(v))
w.WriteByte('"')
}
w.WriteByte('}')
}
func encodeLogAttrsJSON(w byteSliceWriter, attrs []*Attr) {
w.WriteByte('{')
attrsLen := len(attrs)
for i, attr := range attrs {
w.WriteByte('"')
encodeStringJSON(w, attr.Key)
w.WriteString(`": "`)
encodeStringJSON(w, fmt.Sprint(attr.Value))
w.WriteByte('"')
if i != attrsLen-1 {
w.WriteString(`, `)
}
}
w.WriteByte('}')
}
// modified from Go stdlib: encoding/json/encode.go:787-862 (approx)
func encodeStringJSON(e byteSliceWriter, s string) {
for i := 0; i < len(s); {
if b := s[i]; b < utf8.RuneSelf {
i++
if 0x20 <= b && b != '\\' && b != '"' {
e.WriteByte(b)
continue
}
switch b {
case '\\', '"':
e.WriteByte('\\')
e.WriteByte(b)
case '\n':
e.WriteByte('\\')
e.WriteByte('n')
case '\r':
e.WriteByte('\\')
e.WriteByte('r')
case '\t':
e.WriteByte('\\')
e.WriteByte('t')
default:
// This encodes bytes < 0x20 except for escapes above
e.WriteString(`\u00`)
e.WriteByte(hex[b>>4])
e.WriteByte(hex[b&0xF])
}
continue
}
c, size := utf8.DecodeRuneInString(s[i:])
if c == utf8.RuneError && size == 1 {
e.WriteString(`\ufffd`)
i++
continue
}
// U+2028 is LINE SEPARATOR.
// U+2029 is PARAGRAPH SEPARATOR.
// They are both technically valid characters in JSON strings,
// but don't work in JSONP, which has to be evaluated as JavaScript,
// and can lead to security holes there. It is valid JSON to
// escape them, so do so unconditionally.
// See http://timelessrepo.com/json-isnt-a-javascript-subset
if c == '\u2028' || c == '\u2029' {
e.WriteString(`\u202`)
e.WriteByte(hex[c&0xF])
i += size
continue
}
e.WriteString(s[i : i+size])
i += size
}
}