This repository has been archived by the owner on Jun 3, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 1
/
formatter_cli.go
98 lines (84 loc) · 1.84 KB
/
formatter_cli.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
package rz
import (
"bytes"
"encoding/json"
"fmt"
"sort"
"strconv"
"time"
)
// FormatterCLI prettify output suitable for command-line interfaces.
func FormatterCLI() LogFormatter {
return func(ev *Event) ([]byte, error) {
var event map[string]interface{}
var ret = new(bytes.Buffer)
d := json.NewDecoder(bytes.NewReader(ev.buf))
d.UseNumber()
err := d.Decode(&event)
if err != nil {
return ret.Bytes(), err
}
lvlColor := cReset
level := ""
if l, ok := event[ev.levelFieldName].(string); ok {
lvlColor = levelColor(l)
level = l
}
message := ""
if m, ok := event[ev.messageFieldName].(string); ok {
message = m
}
if level != "" {
ret.WriteString(colorize(levelSymbol(level), lvlColor))
}
ret.WriteString(message)
fields := make([]string, 0, len(event))
for field := range event {
switch field {
case ev.timestampFieldName, ev.messageFieldName, ev.levelFieldName:
continue
}
fields = append(fields, field)
}
sort.Strings(fields)
for _, field := range fields {
if needsQuote(field) {
field = strconv.Quote(field)
}
fmt.Fprintf(ret, " %s=", colorize(field, lvlColor))
switch value := event[field].(type) {
case string:
if len(value) == 0 {
ret.WriteString("\"\"")
} else if needsQuote(value) {
ret.WriteString(strconv.Quote(value))
} else {
ret.WriteString(value)
}
case time.Time:
ret.WriteString(value.Format(time.RFC3339))
default:
b, err := json.Marshal(value)
if err != nil {
fmt.Fprintf(ret, "[error: %v]", err)
} else {
fmt.Fprint(ret, string(b))
}
}
}
ret.WriteByte('\n')
return ret.Bytes(), nil
}
}
func levelSymbol(level string) string {
switch level {
case "info":
return "✔ "
case "warning":
return "⚠ "
case "error", "fatal":
return "✘ "
default:
return "• "
}
}