-
Notifications
You must be signed in to change notification settings - Fork 0
/
formatter.go
63 lines (47 loc) · 1.12 KB
/
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 ylog
import (
"encoding/json"
"strings"
)
type (
Formatter interface {
Format(r Record) (string, error)
}
LineFormatter struct {
}
JsonFormatter struct {
}
)
func NewLineFormatter() Formatter {
return &LineFormatter{}
}
func NewJsonFormatter() Formatter {
return &JsonFormatter{}
}
func (l LineFormatter) Format(r Record) (string, error) {
var builder strings.Builder
builder.WriteString(r.Time.Format("2006-01-02 15:04:05"))
builder.WriteString(" ")
builder.WriteString(strings.ToUpper(r.Level.String()))
builder.WriteString(" ")
builder.WriteString(r.Msg)
for k, v := range r.Fields {
builder.WriteString(" ")
builder.WriteString(k)
builder.WriteString("=")
builder.WriteString(InterfaceToStr(v))
}
builder.WriteString("\n")
return builder.String(), nil
}
func (j JsonFormatter) Format(r Record) (string, error) {
newdata := make(Fields, 3+len(r.Fields))
newdata["time"] = r.Time.Format("2006-01-02 15:04:05")
newdata["level"] = r.Level.String()
newdata["msg"] = r.Msg
for k, v := range r.Fields {
newdata[k] = v
}
str, _ := json.Marshal(newdata)
return string(str) + "\n", nil
}