-
Notifications
You must be signed in to change notification settings - Fork 1
/
prettylogzap.go
117 lines (101 loc) · 2.57 KB
/
prettylogzap.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
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
package prettylogzap
import (
"errors"
"net/url"
"os"
"github.com/fatih/color"
"go.uber.org/zap"
"go.uber.org/zap/zapcore"
)
type (
parsedLine struct {
Timestamp string
Logger string
Caller string
Level string
Message string
Fields [][]string
}
colorPadding struct {
color *color.Color
padding int
}
settings struct {
level map[string]colorPadding
timestamp colorPadding
logger colorPadding
caller colorPadding
message colorPadding
}
)
var (
defaultColor = color.New(color.FgWhite)
prettySettings = settings{
level: map[string]colorPadding{},
timestamp: colorPadding{color.New(color.FgYellow), 0},
logger: colorPadding{color.New(color.FgWhite), 10},
caller: colorPadding{color.New(color.FgWhite), 20},
message: colorPadding{color.New(color.FgWhite, color.Bold), 30},
}
colors = map[string]*color.Color{
"debug": color.New(color.FgMagenta),
"info": color.New(color.FgBlue),
"warn": color.New(color.FgYellow),
"error": color.New(color.FgRed),
"fatal": color.New(color.FgRed, color.Bold),
}
ErrNonParseableLine = errors.New("line could not be parsed")
ErrInvalidColor = errors.New("invalid color")
ErrInvalidName = errors.New("invalid name")
ErrOutputPath = errors.New("invalid output path")
)
func (s *settings) parseLevel(levelName string) colorPadding {
if cp, found := s.level[levelName]; found {
return cp
}
if c, exists := colors[levelName]; exists {
s.level[levelName] = colorPadding{c, 5}
} else {
s.level[levelName] = colorPadding{defaultColor, 5}
}
return s.level[levelName]
}
func SetColorPadding(name string, c *color.Color, padding int) error {
if c == nil {
return ErrInvalidColor
}
cp := colorPadding{c, padding}
switch name {
case "timestamp":
prettySettings.timestamp = cp
case "logger":
prettySettings.logger = cp
case "caller":
prettySettings.caller = cp
case "message":
prettySettings.message = cp
case "debug":
prettySettings.level["debug"] = cp
case "info":
prettySettings.level["info"] = cp
case "warn":
prettySettings.level["warn"] = cp
case "error":
prettySettings.level["error"] = cp
default:
return ErrInvalidName
}
return nil
}
func NewPrettySink(encoderConfig zapcore.EncoderConfig) func(u *url.URL) (zap.Sink, error) {
factory := func(u *url.URL) (zap.Sink, error) {
switch u.Host {
case "stdout":
return prettySink{Sink: os.Stdout, encoderConfig: encoderConfig}, nil
case "stderr":
return prettySink{Sink: os.Stderr, encoderConfig: encoderConfig}, nil
}
return nil, ErrOutputPath
}
return factory
}