/
fancylog.go
85 lines (73 loc) · 1.82 KB
/
fancylog.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
package fancylog
import (
"github.com/gookit/color"
"github.com/sirupsen/logrus"
"sort"
)
// Formatter formats log output
type Formatter struct {
Level int
}
// DefaultIndent is the spacing for any output
const DefaultIndent = " "
// Format renders a single log entry
func (f *Formatter) Format(entry *logrus.Entry) ([]byte, error) {
var res []byte
for i := 0; i < f.Level; i++ {
res = append(res, []byte(" ")...)
}
step, ok := entry.Data["step"]
if ok {
res = append(res, []byte(color.Sprintf("<fg=black;bg=white> step %02d </>", step))...)
res = append(res, ' ')
} else {
res = append(res, []byte(" ")...)
}
emoji, ok := entry.Data["emoji"]
if ok {
res = append(res, []byte(emoji.(string))...)
res = append(res, []byte(" ")...)
} else {
res = append(res, []byte(" ")...)
}
var cl *color.Theme
switch entry.Level {
case logrus.DebugLevel:
cl = color.Debug
case logrus.InfoLevel:
cl = color.Info
case logrus.WarnLevel:
cl = &color.Theme{Name: "warning", Style: color.Style{color.Yellow}}
case logrus.ErrorLevel:
cl = color.Error
case logrus.FatalLevel:
cl = color.Danger
}
res = append(res, []byte(cl.Sprintf("%-44s", entry.Message))...)
var keys []string
for k := range entry.Data {
if k == "step" || k == "emoji" {
continue
}
keys = append(keys, k)
}
sort.Slice(keys, func(i, j int) bool { return keys[i] < keys[j] })
for _, k := range keys {
v := entry.Data[k]
if _, ok := v.(string); ok {
res = append(res, []byte(color.FgDarkGray.Sprintf("%s=\"%s\" ", k, v))...)
} else {
res = append(res, []byte(color.FgDarkGray.Sprintf("%s=%v ", k, v))...)
}
}
res = append(res, '\n')
return res, nil
}
// Push increases the level by one
func (f *Formatter) Push() {
f.Level++
}
// Pop decreases the level by one
func (f *Formatter) Pop() {
f.Level--
}