Repository navigation
Expand file tree
/
Copy pathencoder_json.go
More file actions
393 lines (308 loc) · 9.01 KB
/
Copy pathencoder_json.go
File metadata and controls
393 lines (308 loc) · 9.01 KB
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
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
// Copyright © 2020. All rights reserved.
// Author: Ilya Stroy.
// Contacts: [email protected], https://github.com/qioalice
// License: https://opensource.org/licenses/MIT
package ekalog
import (
"time"
"github.com/qioalice/ekago/v2/ekasys"
"github.com/qioalice/ekago/v2/internal/ekafield"
"github.com/qioalice/ekago/v2/internal/ekaletter"
"github.com/json-iterator/go"
)
//noinspection GoSnakeCaseUsage
type (
// CI_JSONEncoder is a type that built to be used as a part of CommonIntegrator
// as an log Entries encoder to the some output as JSON.
// Custom indentation supported.
//
// If you want to use CI_JSONEncoder, you need to instantiate object,
// set indentation (if you need, default is 0) and then call
// FreezeAndGetEncoder() method. By that you'll get the function that has
// an alias CI_Encoder and you can add it as encoder by
// CommonIntegrator.WithEncoder().
//
// See https://github.com/qioalice/ekago/ekalog/integrator.go ,
// https://github.com/qioalice/ekago/ekalog/integrator_common.go for more info.
CI_JSONEncoder struct {
// You know what is JSON indent (pretty JSON, etc), right?
// How much spaces will be added to the beginning of line for each
// nested JSON entity for each nesting level.
//
// So, for indent == 4, you will get:
//
// {
// "key1": "value",
// "nested": {
// "nested_key": "value"
// }
// }
//
// So, keys for 1st nesting level JSON entities has 4 spaces before
// ("key1", "nested") and for 2nd nesting level - 8 spaces before
// ("nested_key").
//
// You may set this value using SetIndent() method.
indent int
// api is jsoniter's API object.
// Created at the first FreezeAndGetEncoder() call for object.
// Won't be called twice. Only one.
//
// See FreezeAndGetEncoder() and doBuild() methods for more info.
api jsoniter.API
}
)
var (
// Make sure we won't break API by declaring package's console encoder
defaultJSONEncoder CI_Encoder
)
//
func (je *CI_JSONEncoder) SetIndent(num int) *CI_JSONEncoder {
if num >= 0 {
je.indent = num
}
return je
}
// FreezeAndGetEncoder builds current CI_JSONEncoder if it has not built yet
// returning a function (has an alias CI_Encoder) that can be used at the
// CommonIntegrator.WithEncoder() call while initializing.
func (je *CI_JSONEncoder) FreezeAndGetEncoder() CI_Encoder {
return je.doBuild().encode
}
// doBuild builds the current CI_JSONEncoder only if it has not built yet.
// There is no-op if encoder already built.
func (je *CI_JSONEncoder) doBuild() *CI_JSONEncoder {
switch {
case je == nil:
return nil
case je.api != nil:
// do not build if it's so already
return je
}
je.api = jsoniter.Config{
IndentionStep: je.indent,
MarshalFloatWith6Digits: true,
EscapeHTML: false,
SortMapKeys: false,
UseNumber: false,
DisallowUnknownFields: false,
TagKey: "",
OnlyTaggedField: false,
ValidateJsonRawMessage: false,
ObjectFieldMustBeSimpleString: true,
CaseSensitive: false,
}.Froze()
return je
}
//
func (je *CI_JSONEncoder) encode(e *Entry) []byte {
s := je.api.BorrowStream(nil)
defer je.api.ReturnStream(s)
var (
allowEmpty = e.LogLetter.Items.Flags.TestAll(FLAG_INTEGRATOR_IGNORE_EMPTY_PARTS)
)
s.WriteObjectStart()
je.encodeBase(s, e, allowEmpty)
s.WriteMore()
wasAdded :=
je.encodeFields(s, allowEmpty, e.LogLetter.Items.Fields)
if wasAdded {
s.WriteMore()
}
wasAdded =
je.encodeStacktrace(s, e, allowEmpty)
if wasAdded {
s.WriteMore()
}
// ------------ Add new sections here ------------ //
// We writing the JSON's comma at the each section, expecting that the next
// section will be written too. But it might be an empty.
// So, we need to remove the last comma. There is no more sections to be written.
b := s.Buffer()
s.SetBuffer(b[:len(b)-1])
s.WriteObjectEnd()
b = s.Buffer()
copied := make([]byte, len(b) +1)
copy(copied, b)
copied[len(copied)-1] = '\n'
return copied
}
// encodeBase encodes e's level, timestamp, message to s.
func (je *CI_JSONEncoder) encodeBase(s *jsoniter.Stream, e *Entry, allowEmpty bool) {
s.WriteObjectField("level")
s.WriteString(e.Level.String())
s.WriteMore()
s.WriteObjectField("level_value")
s.WriteUint8(uint8(e.Level))
s.WriteMore()
s.WriteObjectField("time")
s.WriteString(e.Time.Format(time.UnixDate))
if e.ErrLetter != nil {
s.WriteMore()
je.encodeError(s, e.ErrLetter, allowEmpty)
}
if len(e.LogLetter.Items.Message) > 0 || allowEmpty {
s.WriteMore()
s.WriteObjectField("message")
s.WriteString(e.LogLetter.Items.Message)
}
}
//
func (je *CI_JSONEncoder) encodeError(s *jsoniter.Stream, errLetter *ekaletter.Letter, allowEmpty bool) {
for i, n := 0, len(errLetter.SystemFields); i < n; i++ {
switch errLetter.SystemFields[i].BaseType() {
case ekafield.KIND_SYS_TYPE_EKAERR_UUID:
s.WriteObjectField("error_id")
s.WriteString(errLetter.SystemFields[i].SValue)
case ekafield.KIND_SYS_TYPE_EKAERR_CLASS_ID:
s.WriteObjectField("error_class_id")
s.WriteInt64(errLetter.SystemFields[i].IValue)
case ekafield.KIND_SYS_TYPE_EKAERR_CLASS_NAME:
s.WriteObjectField("error_class_name")
s.WriteString(errLetter.SystemFields[i].SValue)
case ekafield.KIND_SYS_TYPE_EKAERR_PUBLIC_MESSAGE:
if publicMessage := errLetter.SystemFields[i].SValue; len(publicMessage) > 0 || allowEmpty {
s.WriteObjectField("error_public_message")
s.WriteString(publicMessage)
if i < n-1 {
s.WriteMore()
}
}
continue
}
if i < n-1 {
s.WriteMore()
}
}
}
//
func (je *CI_JSONEncoder) encodeStacktrace(
s *jsoniter.Stream,
e *Entry,
allowEmpty bool,
) (wasAdded bool) {
stacktrace := e.LogLetter.StackTrace
if len(stacktrace) == 0 && e.ErrLetter != nil {
stacktrace = e.ErrLetter.StackTrace
}
lStacktrace := int16(len(stacktrace))
if lStacktrace == 0 && !allowEmpty {
return false
}
s.WriteObjectField("stacktrace")
letterItem := (*ekaletter.LetterItem)(nil)
letterItemIdx := int16(0)
if e.ErrLetter != nil {
letterItem = e.ErrLetter.Items
letterItemIdx = letterItem.StackFrameIdx()
}
if lStacktrace > 0 {
s.WriteArrayStart()
for i := int16(0); i < lStacktrace; i++ {
letterItemPassed := (*ekaletter.LetterItem)(nil)
if letterItem != nil && letterItemIdx == i {
letterItemPassed = letterItem
letterItem = letterItem.Next()
letterItemIdx = letterItem.StackFrameIdx()
}
je.encodeStackFrame(s, stacktrace[i], letterItemPassed, allowEmpty)
if i < lStacktrace-1 {
s.WriteMore()
}
}
s.WriteArrayEnd()
} else {
s.WriteEmptyArray()
}
return true
}
//
func (je *CI_JSONEncoder) encodeStackFrame(
s *jsoniter.Stream,
frame ekasys.StackFrame,
letterItem *ekaletter.LetterItem,
allowEmpty bool,
) {
frame.DoFormat()
s.WriteObjectStart()
s.WriteObjectField("func")
s.WriteString(frame.Format[:frame.FormatFileOffset-1])
s.WriteMore()
s.WriteObjectField("file")
s.WriteString(frame.Format[frame.FormatFileOffset+1 : frame.FormatFullPathOffset-2])
s.WriteMore()
s.WriteObjectField("package")
s.WriteString(frame.Format[frame.FormatFullPathOffset:])
if letterItem != nil {
if len(letterItem.Message) > 0 || allowEmpty {
s.WriteMore()
s.WriteObjectField("message")
s.WriteString(letterItem.Message)
}
if len(letterItem.Fields) > 0 || allowEmpty {
s.WriteMore()
je.encodeFields(s, allowEmpty, letterItem.Fields)
}
}
s.WriteObjectEnd()
}
// JsonEncodeFields is JSON encoding helper that encodes 'fields' as JSON array,
// adding it to the JSON document's root with the key "fields".
//
// Puts JSON encoded data into 's' stream,
// doing nothing if 'fields' is empty and 'allowEmpty' is false.
//
func (je *CI_JSONEncoder) encodeFields(
s *jsoniter.Stream,
allowEmpty bool,
fields []ekafield.Field,
) (wasAdded bool) {
emptySet := len(fields) == 0
if emptySet && !allowEmpty {
return false
}
s.WriteObjectField("fields")
if emptySet {
s.WriteEmptyArray()
return true
}
unnamedFieldIdx := 1
s.WriteArrayStart()
for i, n := int16(0), int16(len(fields)); i < n; i++ {
je.encodeField(s, fields[i], &unnamedFieldIdx)
s.WriteMore()
}
b := s.Buffer()
s.SetBuffer(b[:len(b)-1]) // remove last comma
s.WriteArrayEnd()
return true
}
// JsonEncodeField is JSON encoding helper that encodes 'f' field as JSON object
// adding it to the JSON document. Uses 'unnamedFieldIdx' as a number
// that will be transformed into string "unnamed_<number>" and that string will
// be used as field's key if its key is empty.
//
// Puts JSON encoded data into 's' stream.
//
func (je *CI_JSONEncoder) encodeField(
s *jsoniter.Stream,
f ekafield.Field,
unnamedFieldIdx *int,
) {
s.WriteObjectStart()
s.WriteObjectField("key")
s.WriteString(f.KeyOrUnnamed(unnamedFieldIdx))
s.WriteMore()
// TODO: write kind if requested
s.WriteObjectField("value")
if !f.Kind.IsNil() {
if f.SValue != "" {
s.WriteString(f.SValue)
} else {
_, _ = f.ValueWriteTo(s)
}
} else {
s.WriteNil()
}
s.WriteObjectEnd()
}