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 0
/
formatter_console.go
130 lines (113 loc) · 2.4 KB
/
formatter_console.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
package rz
import (
"bytes"
"encoding/json"
"fmt"
"sort"
"strconv"
"strings"
)
const (
cReset = 0
cBold = 1
cRed = 31
cGreen = 32
cYellow = 33
cBlue = 34
cMagenta = 35
cCyan = 36
cGray = 37
cDarkGray = 90
)
// FormatterConsole prettify output for human cosumption
func FormatterConsole() 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[DefaultLevelFieldName].(string); ok {
lvlColor = levelColor(l)
level = strings.ToUpper(l)[0:4]
}
message := ""
if m, ok := event[DefaultMessageFieldName].(string); ok {
message = m
}
timestamp := ""
if t, ok := event[DefaultTimestampFieldName].(string); ok {
timestamp = t
}
ret.WriteString(fmt.Sprintf("%-20s |%-4s|",
timestamp,
colorize(level, lvlColor),
))
if message != "" {
ret.WriteString(" " + message)
}
fields := make([]string, 0, len(event))
for field := range event {
switch field {
case DefaultTimestampFieldName, DefaultMessageFieldName, DefaultLevelFieldName:
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)
}
default:
b, err := json.Marshal(value)
if err != nil {
return ret.Bytes(), err
}
fmt.Fprint(ret, string(b))
}
}
ret.WriteByte('\n')
return ret.Bytes(), nil
}
}
func colorize(s interface{}, color int) string {
return fmt.Sprintf("\x1b[%dm%v\x1b[0m", color, s)
}
func levelColor(level string) int {
switch level {
case "debug":
return cMagenta
case "info":
return cCyan
case "warning":
return cYellow
case "error", "fatal", "panic":
return cRed
default:
return cReset
}
}
func needsQuote(s string) bool {
for i := range s {
if s[i] < 0x20 || s[i] > 0x7e || s[i] == ' ' || s[i] == '\\' || s[i] == '"' {
return true
}
}
return false
}