/
options.go
127 lines (112 loc) · 2.16 KB
/
options.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
118
119
120
121
122
123
124
125
126
127
package logger
import (
"context"
"io"
"go.uber.org/zap/zapcore"
)
const (
// defaultCallerSkip .
defaultCallerSkip = 1
// defaultDateFormat date format
defaultDateFormat = "2006-01-02 15:04:05.000"
)
// ContextHook return new Logger with context
type ContextHook func(ctx context.Context) string
// options .
type options struct {
// name 名称
name string
// callerSkip 跳过的调用者数量
callerSkip int
// levelEncoder .
levelEncoder func(code zapcore.Level) string
// writer others output
writer io.Writer
// contextHook parse name in context. eg: TestContextHook
contextHook ContextHook
// minlevel convert MinLevel to levelEncoder
minlevel zapcore.Level
}
// option .
type option interface {
apply(o *options)
}
// funcOption .
type funcOption func(o *options)
// apply .
func (f funcOption) apply(o *options) () {
f(o)
}
// WithName .
func WithName(v string) option {
return funcOption(
func(o *options) {
o.name = v
},
)
}
// WithCallerSkip .
func WithCallerSkip(v int) option {
return funcOption(
func(o *options) {
o.callerSkip = v
},
)
}
// WithColorful .
func WithColorful() option {
return funcOption(
func(o *options) {
o.levelEncoder = colorfulEncoder
},
)
}
// WithMinLevel .
func WithMinLevel(v string) option {
return funcOption(
func(o *options) {
minlevel := zapcore.DebugLevel
switch v {
case "debug":
minlevel = zapcore.DebugLevel
case "info":
minlevel = zapcore.InfoLevel
case "warn":
minlevel = zapcore.WarnLevel
case "error":
minlevel = zapcore.ErrorLevel
case "fatal":
minlevel = zapcore.FatalLevel
}
o.minlevel = minlevel
},
)
}
// WithWriter .
func WithWriter(v io.Writer) option {
return funcOption(
func(o *options) {
o.writer = v
},
)
}
// WithContextHook .
func WithContextHook(hook ContextHook) option {
return funcOption(
func(o *options) {
o.contextHook = hook
},
)
}
// configuration .
func configuration(opts ...option) *options {
var options = &options{
callerSkip: defaultCallerSkip,
levelEncoder: originEncoder,
minlevel: zapcore.DebugLevel,
}
for _, opt := range opts {
opt.apply(options)
}
return options
}