This repository has been archived by the owner on Mar 31, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 7
/
json.go
305 lines (289 loc) · 6.67 KB
/
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
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
package log
import (
"encoding"
"encoding/json"
"fmt"
"reflect"
"strconv"
"strings"
"time"
"unicode/utf8"
)
// JSONFormat implements Formatter for JSON Lines.
//
// http://jsonlines.org/
type JSONFormat struct {
// Utsname can normally be left blank.
// If not empty, the string is used instead of the hostname.
// Utsname must match this regexp: ^[a-z][a-z0-9-]*$
Utsname string
}
// String returns "json".
func (f JSONFormat) String() string {
return "json"
}
// Format implements Formatter.Format.
func (f JSONFormat) Format(buf []byte, l *Logger, t time.Time, severity int,
msg string, fields map[string]interface{}) ([]byte, error) {
var err error
// assume enough capacity for mandatory fields (except for msg).
buf = append(buf, `{"topic":"`...)
buf = append(buf, l.Topic()...)
buf = append(buf, `","logged_at":"`...)
buf = t.UTC().AppendFormat(buf, RFC3339Micro)
buf = append(buf, `","severity":`...)
if ss, ok := severityMap[severity]; ok {
buf = append(buf, '"')
buf = append(buf, ss...)
buf = append(buf, '"')
} else {
buf = strconv.AppendInt(buf, int64(severity), 10)
}
buf = append(buf, `,"utsname":"`...)
if len(f.Utsname) > 0 {
buf = append(buf, f.Utsname...)
} else {
buf = append(buf, utsname...)
}
buf = append(buf, `","message":`...)
buf, err = appendJSON(buf, msg)
if err != nil {
return nil, err
}
for k, v := range fields {
if !IsValidKey(k) {
return nil, ErrInvalidKey
}
if cap(buf) < (len(k) + 4) {
return nil, ErrTooLarge
}
buf = append(buf, `,"`...)
buf = append(buf, k...)
buf = append(buf, `":`...)
buf, err = appendJSON(buf, v)
if err != nil {
return nil, err
}
}
for k, v := range l.Defaults() {
if _, ok := fields[k]; ok {
continue
}
if cap(buf) < (len(k) + 4) {
return nil, ErrTooLarge
}
buf = append(buf, `,"`...)
buf = append(buf, k...)
buf = append(buf, `":`...)
buf, err = appendJSON(buf, v)
if err != nil {
return nil, err
}
}
if cap(buf) < 2 {
return nil, ErrTooLarge
}
return append(buf, "}\n"...), nil
}
func appendJSON(buf []byte, v interface{}) ([]byte, error) {
var err error
switch t := v.(type) {
case nil:
if cap(buf) < 4 {
return nil, ErrTooLarge
}
return append(buf, "null"...), nil
case bool:
if cap(buf) < 5 { // len("false")
return nil, ErrTooLarge
}
return strconv.AppendBool(buf, t), nil
case time.Time:
// len("2006-01-02T15:04:05.000000Z07:00") + 2
if cap(buf) < 34 {
return nil, ErrTooLarge
}
buf = append(buf, '"')
buf = t.UTC().AppendFormat(buf, RFC3339Micro)
return append(buf, '"'), nil
case int:
// len("-9223372036854775807")
if cap(buf) < 20 {
return nil, ErrTooLarge
}
return strconv.AppendInt(buf, int64(t), 10), nil
case int8:
// len("-128")
if cap(buf) < 4 {
return nil, ErrTooLarge
}
return strconv.AppendInt(buf, int64(t), 10), nil
case int16:
// len("-32768")
if cap(buf) < 6 {
return nil, ErrTooLarge
}
return strconv.AppendInt(buf, int64(t), 10), nil
case int32:
// len("-2147483648")
if cap(buf) < 11 {
return nil, ErrTooLarge
}
return strconv.AppendInt(buf, int64(t), 10), nil
case int64:
// len("-9223372036854775807")
if cap(buf) < 20 {
return nil, ErrTooLarge
}
return strconv.AppendInt(buf, t, 10), nil
case uint:
// len("18446744073709551615")
if cap(buf) < 20 {
return nil, ErrTooLarge
}
return strconv.AppendUint(buf, uint64(t), 10), nil
case uint8:
// len("255")
if cap(buf) < 3 {
return nil, ErrTooLarge
}
return strconv.AppendUint(buf, uint64(t), 10), nil
case uint16:
// len("65535")
if cap(buf) < 5 {
return nil, ErrTooLarge
}
return strconv.AppendUint(buf, uint64(t), 10), nil
case uint32:
// len("4294967295")
if cap(buf) < 10 {
return nil, ErrTooLarge
}
return strconv.AppendUint(buf, uint64(t), 10), nil
case uint64:
// len("18446744073709551615")
if cap(buf) < 20 {
return nil, ErrTooLarge
}
return strconv.AppendUint(buf, t, 10), nil
case float32:
if cap(buf) < 256 {
return nil, ErrTooLarge
}
return strconv.AppendFloat(buf, float64(t), 'f', -1, 32), nil
case float64:
if cap(buf) < 256 {
return nil, ErrTooLarge
}
return strconv.AppendFloat(buf, t, 'f', -1, 64), nil
case string:
if !utf8.ValidString(t) {
// the next line replaces invalid characters.
t = strings.ToValidUTF8(t, string(utf8.RuneError))
}
// escaped length = 2*len(t) + 2 double quotes
if cap(buf) < (len(t)*2 + 2) {
return nil, ErrTooLarge
}
return strconv.AppendQuote(buf, t), nil
case json.Marshaler:
s, err := t.MarshalJSON()
if err != nil {
return nil, err
}
if cap(buf) < len(s) {
return nil, ErrTooLarge
}
// normalize for JSON Lines
for i, b := range s {
if b == '\n' || b == '\r' {
s[i] = ' '
}
}
return append(buf, s...), nil
case encoding.TextMarshaler:
// TextMarshaler encodes into UTF-8 string.
s, err := t.MarshalText()
if err != nil {
return nil, err
}
if cap(buf) < (len(s)*2 + 2) {
return nil, ErrTooLarge
}
return strconv.AppendQuote(buf, string(s)), nil
case error:
s := t.Error()
if !utf8.ValidString(s) {
// the next line replaces invalid characters.
s = strings.ToValidUTF8(s, string(utf8.RuneError))
}
// escaped length = 2*len(s) + 2 double quotes
if cap(buf) < (len(s)*2 + 2) {
return nil, ErrTooLarge
}
return strconv.AppendQuote(buf, s), nil
}
value := reflect.ValueOf(v)
typ := value.Type()
kind := typ.Kind()
// string-keyed maps
if kind == reflect.Map && typ.Key().Kind() == reflect.String {
if cap(buf) < 1 {
return nil, ErrTooLarge
}
buf = append(buf, '{')
first := true
for _, k := range value.MapKeys() {
if !first {
if cap(buf) < 1 {
return nil, ErrTooLarge
}
buf = append(buf, ',')
}
buf, err = appendJSON(buf, k.String())
if err != nil {
return nil, err
}
if cap(buf) < 1 {
return nil, ErrTooLarge
}
buf = append(buf, ':')
buf, err = appendJSON(buf, value.MapIndex(k).Interface())
if err != nil {
return nil, err
}
first = false
}
if cap(buf) < 1 {
return nil, ErrTooLarge
}
return append(buf, '}'), nil
}
// slices and arrays
if kind == reflect.Slice || kind == reflect.Array {
if cap(buf) < 1 {
return nil, ErrTooLarge
}
buf = append(buf, '[')
first := true
for i := 0; i < value.Len(); i++ {
if !first {
if cap(buf) < 1 {
return nil, ErrTooLarge
}
buf = append(buf, ',')
}
buf, err = appendJSON(buf, value.Index(i).Interface())
if err != nil {
return nil, err
}
first = false
}
if cap(buf) < 1 {
return nil, ErrTooLarge
}
return append(buf, ']'), nil
}
// other types are just formatted as a string with "%#v".
return appendJSON(buf, fmt.Sprintf("%#v", v))
}