-
Notifications
You must be signed in to change notification settings - Fork 13
/
main.go
497 lines (399 loc) · 12.5 KB
/
main.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
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
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
package main
import (
"bufio"
"bytes"
"encoding/json"
"errors"
"flag"
"fmt"
"io"
"io/ioutil"
"log"
"math"
"os"
"strings"
"time"
"github.com/logrusorgru/aurora"
. "github.com/logrusorgru/aurora"
)
// Provided via ldflags by goreleaser automatically
var (
version = "dev"
commit = "none"
date = "unknown"
)
var (
debug = log.New(ioutil.Discard, "", 0)
debugEnabled = false
severityToColor map[string]Color
)
var errNonZapLine = errors.New("non-zap line")
func init() {
if os.Getenv("ZAP_PRETTY_DEBUG") != "" {
debug = log.New(os.Stderr, "[pretty-debug] ", 0)
debugEnabled = true
}
severityToColor = make(map[string]Color)
severityToColor["debug"] = BlueFg
severityToColor["info"] = GreenFg
severityToColor["warning"] = BrownFg
severityToColor["error"] = RedFg
severityToColor["dpanic"] = RedFg
severityToColor["panic"] = RedFg
severityToColor["fatal"] = RedFg
}
type processorOption interface {
apply(p *processor)
}
type processorOptionFunc func(p *processor)
func (f processorOptionFunc) apply(p *processor) {
f(p)
}
func withAllFields() processorOption {
return processorOptionFunc(func(p *processor) {
p.showAllFields = true
})
}
type processor struct {
scanner *bufio.Scanner
output io.Writer
showAllFields bool
}
var (
showAllFlag = flag.Bool("all", false, "Show ")
versionFlag = flag.Bool("version", false, "Prints version information and exit")
multilineJSONStartingFromLenFlag = flag.Int("n", 3, "Format JSON as multiline if got more than n elements in data")
)
var showAll = false
func main() {
flag.Parse()
if *versionFlag {
printVersion()
os.Exit(0)
}
go NewSignaler().forwardAllSignalsToProcessGroup()
// FIXME: How could we make it more resilient to we simply drop the line instead? Would that mean our own "scanner"?
// New scanner with a maximum of 250MiB per line, pass that, we panic.
scanner := bufio.NewScanner(os.Stdin)
scanner.Buffer(nil, 250*1024*1024)
processor := &processor{
scanner: scanner,
output: os.Stdout,
showAllFields: *showAllFlag,
}
processor.process()
}
func printVersion() {
fmt.Printf("zap-pretty %s (commit: %s, date: %v)\n", version, commit, date)
}
func (p *processor) process() {
first := true
for p.scanner.Scan() {
if !first {
fmt.Fprintln(p.output)
}
p.processLine(p.scanner.Text())
first = false
}
if err := p.scanner.Err(); err != nil {
debugPrintln("Scanner terminated with error: %w", err)
}
}
func (p *processor) processLine(line string) {
defer func() {
if err := recover(); err != nil {
p.unformattedPrintLine(line, "Panic occurred while processing line '%s', ending processing (%s)", line, err)
}
}()
debugPrintln("Processing line: %s", line)
reader := bytes.NewReader([]byte(line))
decoder := json.NewDecoder(reader)
token, err := decoder.Token()
if err != nil {
p.unformattedPrintLine(line, "Does not look like a JSON line, ending processing (%s)", err)
return
}
delim, ok := token.(json.Delim)
if !ok || delim != '{' {
p.unformattedPrintLine(line, "Expecting a JSON object delimited, ending processing")
return
}
lineData := map[string]interface{}{}
for decoder.More() {
token, err := decoder.Token()
if err != nil {
p.unformattedPrintLine(line, "Invalid JSON key in line, ending processing (%s)", err)
return
}
key := token.(string)
// if keys[key] {
// // Key duplicated here ...
// }
// keys[key] = true
var value interface{}
if err := decoder.Decode(&value); err != nil {
p.unformattedPrintLine(line, "Invalid JSON value in line, ending processing (%s)", err)
return
}
lineData[key] = value
}
// Read the ending delimiter of the JSON object
if _, err := decoder.Token(); err != nil {
p.unformattedPrintLine(line, "Invalid JSON, misssing object end delimiter in line, ending processing (%s)", err)
return
}
prettyLine, err := p.maybePrettyPrintLine(line, lineData)
if err != nil {
fmt.Fprint(p.output, line)
switch err {
case errNonZapLine:
debugPrintln("Not a known zap line format")
default:
debugPrintln("Not printing line due to error: %s", err)
}
} else {
fmt.Fprint(p.output, prettyLine)
}
}
func (p *processor) maybePrettyPrintLine(line string, lineData map[string]interface{}) (string, error) {
if lineData["level"] != nil && lineData["ts"] != nil && lineData["msg"] != nil {
return p.maybePrettyPrintZapLine(line, lineData)
}
if lineData["severity"] != nil && (lineData["time"] != nil || lineData["timestamp"] != nil) && lineData["message"] != nil {
return p.maybePrettyPrintZapdriverLine(line, lineData)
}
return "", errNonZapLine
}
func (p *processor) maybePrettyPrintZapLine(line string, lineData map[string]interface{}) (string, error) {
logTimestamp, err := tsFieldToTimestamp(lineData["ts"])
if err != nil {
return "", fmt.Errorf("unable to process field 'ts': %w", err)
}
var caller *string
if v := lineData["caller"]; v != nil {
callerStr := v.(string)
caller = &callerStr
}
var logger *string
if v := lineData["logger"]; v != nil {
loggerStr := v.(string)
logger = &loggerStr
}
var buffer bytes.Buffer
p.writeHeader(&buffer, logTimestamp, lineData["level"].(string), caller, logger, lineData["msg"].(string))
// Delete standard stuff from data fields
delete(lineData, "level")
delete(lineData, "ts")
delete(lineData, "caller")
delete(lineData, "logger")
delete(lineData, "msg")
stacktrace := ""
if t, ok := lineData["stacktrace"].(string); ok && t != "" {
delete(lineData, "stacktrace")
stacktrace = t
}
p.writeJSON(&buffer, lineData)
if stacktrace != "" {
p.writeErrorDetails(&buffer, "", stacktrace)
}
return buffer.String(), nil
}
var zeroTime = time.Time{}
func tsFieldToTimestamp(input interface{}) (*time.Time, error) {
switch v := input.(type) {
case float64:
nanosSinceEpoch := v * time.Second.Seconds()
secondsPart, nanosPart := math.Modf(nanosSinceEpoch)
timestamp := time.Unix(int64(secondsPart), int64(nanosPart/time.Nanosecond.Seconds()))
return ×tamp, nil
case string:
timestamp, err := time.Parse(time.RFC3339Nano, v)
timestamp = timestamp.Local()
return ×tamp, err
}
return &zeroTime, fmt.Errorf("don't know how to turn %T (value %s) into a time.Time object", input, input)
}
func (p *processor) maybePrettyPrintZapdriverLine(line string, lineData map[string]interface{}) (string, error) {
timeField := "time"
timeValue := lineData[timeField]
if lineData[timeField] == nil {
timeField = "timestamp"
timeValue = lineData[timeField]
}
var buffer bytes.Buffer
parsedTime, err := tsFieldToTimestamp(timeValue)
if err != nil {
return "", fmt.Errorf("unable to process field %q: %w", timeField, err)
}
var caller *string
if v := lineData["caller"]; v != nil {
callerStr := v.(string)
caller = &callerStr
}
var logger *string
if v := lineData["logger"]; v != nil {
loggerStr := v.(string)
logger = &loggerStr
}
p.writeHeader(&buffer, parsedTime, lineData["severity"].(string), caller, logger, lineData["message"].(string))
// Delete standard stuff from data fields
delete(lineData, timeField)
delete(lineData, "severity")
delete(lineData, "caller")
delete(lineData, "logger")
delete(lineData, "message")
if !p.showAllFields {
delete(lineData, "labels")
delete(lineData, "serviceContext")
delete(lineData, "logging.googleapis.com/labels")
delete(lineData, "logging.googleapis.com/sourceLocation")
}
errorVerbose := ""
if t, ok := lineData["errorVerbose"].(string); ok && t != "" {
delete(lineData, "errorVerbose")
errorVerbose = t
}
stacktrace := ""
if t, ok := lineData["stacktrace"].(string); ok && t != "" {
delete(lineData, "stacktrace")
stacktrace = t
}
p.writeJSON(&buffer, lineData)
if errorVerbose != "" || stacktrace != "" {
p.writeErrorDetails(&buffer, errorVerbose, stacktrace)
}
return buffer.String(), nil
}
func (p *processor) writeHeader(buffer *bytes.Buffer, timestamp *time.Time, severity string, caller *string, logger *string, message string) {
buffer.WriteString(fmt.Sprintf("[%s]", timestamp.Format("2006-01-02 15:04:05.000 MST")))
buffer.WriteByte(' ')
buffer.WriteString(p.colorizeSeverity(severity).String())
if logger != nil && caller != nil {
buffer.WriteByte(' ')
buffer.WriteString(Gray(12, fmt.Sprintf("(%s, %s)", *logger, *caller)).String())
} else if logger != nil {
buffer.WriteByte(' ')
buffer.WriteString(Gray(12, fmt.Sprintf("(%s)", *logger)).String())
} else if caller != nil {
buffer.WriteByte(' ')
buffer.WriteString(Gray(12, fmt.Sprintf("(%s)", *caller)).String())
}
buffer.WriteByte(' ')
buffer.WriteString(Blue(message).String())
}
var temporaryStackSpacer = "_-@\\!/@-_"
func (p *processor) writeErrorDetails(buffer *bytes.Buffer, errorVerbose string, stacktrace string) {
if stacktrace != "" {
buffer.WriteByte('\n')
buffer.WriteString("Stacktrace\n")
buffer.WriteString(" " + strings.ReplaceAll(stacktrace, "\n", "\n "))
}
if stacktrace != "" && errorVerbose != "" {
// If both are present, stacktrace has print something, so let's add an extra empty line here for spacing
buffer.WriteByte('\n')
}
// The `errorVerbose` seems to contain a stack trace for each error captured. This behavior
// comes from `github.com/pkg/errors` that create a stack of errors, each of the item having an associate
// stacktrace.
if errorVerbose != "" {
writeErrorVerbose(buffer, errorVerbose)
}
}
func writeErrorVerbose(buffer *bytes.Buffer, errorVerbose string) {
joinedErrorVerbose := strings.ReplaceAll(errorVerbose, "\n\t", temporaryStackSpacer)
scanner := bufio.NewScanner(strings.NewReader(" " + joinedErrorVerbose))
var linePrevious *string
var lineCurrent *string
startedSection := false
buffer.WriteByte('\n')
buffer.WriteString("Error Verbose\n")
for scanner.Scan() {
if lineCurrent != nil {
linePrevious = lineCurrent
}
line := scanner.Text()
lineCurrent = &line
if linePrevious != nil {
isPreviousStackLine := strings.Contains(*linePrevious, temporaryStackSpacer)
isStackLine := strings.Contains(line, temporaryStackSpacer)
if isStackLine && !isPreviousStackLine {
// This condition means we are at a section boundary, let's add some extra spacing here
writeStackSectionTitle(buffer, *linePrevious)
startedSection = true
} else if isPreviousStackLine {
writeStackLine(buffer, *linePrevious, startedSection, false)
startedSection = false
} else {
buffer.WriteString(*linePrevious)
buffer.WriteByte('\n')
startedSection = false
}
}
}
if lineCurrent != nil {
isStackLine := strings.Contains(*lineCurrent, temporaryStackSpacer)
if isStackLine {
writeStackLine(buffer, *lineCurrent, startedSection, true)
} else {
// It means we have seen more than one line, so we need the extra padding
if linePrevious != nil {
buffer.WriteString(" ")
}
buffer.WriteString(*lineCurrent)
}
}
}
func writeStackSectionTitle(buffer *bytes.Buffer, line string) {
buffer.WriteByte('\n')
buffer.WriteString(" ")
buffer.WriteString(line)
}
func writeStackLine(buffer *bytes.Buffer, line string, isFirstStack, isLastStack bool) {
if isFirstStack {
buffer.WriteByte('\n')
}
buffer.WriteString(" ")
buffer.WriteString(strings.Replace(line, temporaryStackSpacer, "\n \t", 2))
if !isLastStack {
buffer.WriteByte('\n')
}
}
func (p *processor) writeJSON(buffer *bytes.Buffer, data map[string]interface{}) {
if len(data) <= 0 {
return
}
// FIXME: This is poor, we would like to print in a single line stuff that are not too
// big. But what represents a too big value exactly? We would need to serialize to
// JSON, check length, if smaller than threshold, print with space, otherwise
// re-serialize with pretty-printing stuff
var jsonBytes []byte
var err error
if len(data) <= *multilineJSONStartingFromLenFlag {
jsonBytes, err = json.Marshal(data)
} else {
jsonBytes, err = json.MarshalIndent(data, "", " ")
}
if err != nil {
// FIXME: We could print each line as raw text maybe when it's not working?
debugPrintln("Unable to marshal data as JSON: %s", err)
} else {
buffer.WriteByte(' ')
buffer.Write(jsonBytes)
}
}
func (p *processor) colorizeSeverity(severity string) aurora.Value {
color := severityToColor[strings.ToLower(severity)]
if color == 0 {
color = BlueFg
}
return Colorize(strings.ToUpper(severity), color)
}
func (p *processor) unformattedPrintLine(line string, message string, args ...interface{}) {
debugPrintln(message, args...)
fmt.Fprint(p.output, line)
}
func debugPrintln(msg string, args ...interface{}) {
if debugEnabled {
debug.Printf(msg+"\n", args...)
}
}