forked from youpenglai/goutils
-
Notifications
You must be signed in to change notification settings - Fork 0
/
formatter.go
62 lines (53 loc) · 1.18 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
package logger
import (
"time"
"strings"
"fmt"
)
const TimeFormatter = "2006-01-02 15:04:05.000"
type LoggerMsg struct {
Prefix string
Level int
Time time.Time
Caller struct {
FileName string
Line int
}
Msg string
formatter LoggerFormatterFunc
}
type LoggerFormatter interface {
Format(colorful bool) string
}
func levelColor(level int) string {
switch level {
case LevelDebug:
return ConsoleBlue
case LevelInfo:
return ConsoleGreen
case LevelWarn:
return ConsoleYellow
case LevelError:
return ConsoleRed
case LevelAbort:
return ConsoleMagenta
}
return ConsoleReset
}
func (lmsg *LoggerMsg) Format(colorful bool) string {
if lmsg.formatter != nil {
return lmsg.formatter(lmsg, colorful)
}
return lmsg.format(colorful)
}
func (lmsg *LoggerMsg) format(colorful bool) string {
prefix := strings.ToUpper(lmsg.Prefix)
level := levelPrefix[lmsg.Level]
timeString := lmsg.Time.Format(TimeFormatter)
caller := fmt.Sprintf("%s:%d:", lmsg.Caller.FileName, lmsg.Caller.Line)
if colorful {
prefix = ColorText(prefix, ConsoleCyan)
level = ColorText(level, levelColor(lmsg.Level))
}
return fmt.Sprintf("%s %s %s %s %s\n", prefix, timeString, caller, level, lmsg.Msg)
}