forked from doloopwhile/logrusltsv
-
Notifications
You must be signed in to change notification settings - Fork 0
/
formatter.go
61 lines (50 loc) · 1.2 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
package logrusltsv
import (
"bytes"
"fmt"
"sort"
"strconv"
"time"
"github.com/Sirupsen/logrus"
)
type (
Formatter struct{}
byKey [][2]string
)
func (f *Formatter) Format(entry *logrus.Entry) ([]byte, error) {
commonItems := [][2]string{
{"time", entry.Time.Format(time.RFC3339)},
{"level", entry.Level.String()},
{"msg", escape(entry.Message)},
}
items := [][2]string{}
for k, v := range entry.Data {
if k == "time" || k == "msg" || k == "level" {
k = "field." + k
}
items = append(items, [2]string{escape(k), escape(fmt.Sprint(v))})
}
sort.Sort(byKey(items))
return encodeLTSV(append(commonItems, items...)), nil
}
func (items byKey) Len() int { return len(items) }
func (items byKey) Less(i, j int) bool { return items[i][0] < items[j][0] }
func (items byKey) Swap(i, j int) { items[i], items[j] = items[j], items[i] }
func encodeLTSV(items [][2]string) []byte {
b := bytes.Buffer{}
for i, item := range items {
b.WriteString(item[0])
b.WriteString(":")
b.WriteString(item[1])
if i == len(items)-1 {
b.WriteString("\n")
} else {
b.WriteString("\t")
}
}
return b.Bytes()
}
func escape(s string) string {
v := strconv.Quote(s)
return v[1 : len(v)-1]
}