-
Notifications
You must be signed in to change notification settings - Fork 5
/
text_formatter.go
63 lines (56 loc) · 1.46 KB
/
text_formatter.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
package log
import (
"bytes"
"encoding/json"
"fmt"
"sort"
)
var TextFormatter Formatter = textFormatter{}
type textFormatter struct{}
func (f textFormatter) Format(entry *Entry) ([]byte, error) {
var buffer *bytes.Buffer
if entry.Buffer != nil {
buffer = entry.Buffer
} else {
buffer = bytes.NewBuffer(make([]byte, 0, 16<<10))
}
f.appendKeyValue(buffer, fieldKeyTime, FormatTime(entry.Time.In(_beijingLocation)))
f.appendKeyValue(buffer, fieldKeyLevel, entry.Level.String())
f.appendKeyValue(buffer, fieldKeyTraceId, entry.TraceId)
f.appendKeyValue(buffer, fieldKeyLocation, entry.Location)
f.appendKeyValue(buffer, fieldKeyMessage, entry.Message)
if fields := entry.Fields; len(fields) > 0 {
fixFieldsConflictAndHandleErrorFields(fields)
keys := make([]string, 0, len(fields))
for k := range fields {
keys = append(keys, k)
}
sort.Strings(keys)
for _, k := range keys {
v := fields[k]
f.appendKeyValue(buffer, k, v)
}
}
buffer.WriteByte('\n')
return buffer.Bytes(), nil
}
func (f textFormatter) appendKeyValue(b *bytes.Buffer, key string, value interface{}) {
if b.Len() > 0 {
b.WriteString(", ")
}
b.WriteString(key)
b.WriteByte('=')
f.appendValue(b, value)
}
func (f textFormatter) appendValue(b *bytes.Buffer, value interface{}) {
var stringVal string
switch v := value.(type) {
case string:
stringVal = v
case json.RawMessage:
stringVal = string(v)
default:
stringVal = fmt.Sprint(value)
}
b.WriteString(stringVal)
}