-
-
Notifications
You must be signed in to change notification settings - Fork 0
/
formatter.go
88 lines (71 loc) · 1.54 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
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
package main
import (
"bytes"
"fmt"
"strings"
"time"
"github.com/sirupsen/logrus"
)
type Formatter struct {
logrus.Formatter
TimestampFormat string
PrintColors bool
TrimMessages bool
}
func (f Formatter) Format(entry *logrus.Entry) ([]byte, error) {
levelColor := getColorByLevel(entry.Level)
timestampFormat := f.TimestampFormat
if timestampFormat == "" {
timestampFormat = time.StampMilli
}
/* output buffer */
b := &bytes.Buffer{}
/* write timestamp */
if f.PrintColors {
b.WriteString(colorBlack)
}
b.WriteString("[")
b.WriteString(entry.Time.Format(timestampFormat))
b.WriteString("]")
if f.PrintColors {
b.WriteString(colorReset)
}
b.WriteString(" ")
/* write log level */
if f.PrintColors {
_, _ = fmt.Fprint(b, levelColor)
}
b.WriteString(strings.ToUpper(entry.Level.String())[:4])
b.WriteString(" ")
if f.PrintColors {
b.WriteString(colorReset)
}
/* write log message */
if f.TrimMessages {
b.WriteString(strings.TrimSpace(entry.Message))
} else {
b.WriteString(entry.Message)
}
b.WriteByte('\n')
return b.Bytes(), nil
}
const (
colorBlack = "\u001b[90m"
colorRed = "\u001b[91m"
colorGreen = "\u001b[92m"
colorYellow = "\u001b[93m"
colorBlue = "\u001b[94m"
colorReset = "\u001b[0m"
)
func getColorByLevel(level logrus.Level) string {
switch level {
case logrus.DebugLevel, logrus.TraceLevel:
return colorBlue
case logrus.WarnLevel:
return colorYellow
case logrus.ErrorLevel, logrus.FatalLevel, logrus.PanicLevel:
return colorRed
default:
return colorGreen
}
}