-
Notifications
You must be signed in to change notification settings - Fork 3
/
encoder_option.go
98 lines (80 loc) · 1.98 KB
/
encoder_option.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
package zapKit
import "go.uber.org/zap/zapcore"
const (
// OutputFormatConsole 人类可读的多行输出
OutputFormatConsole outputFormat = iota
// OutputFormatJson JSON格式输出
OutputFormatJson
)
type (
outputFormat uint8
encoderOptions struct {
// OutputFormat 输出类型
OutputFormat outputFormat
MessagePrefix string
EncodeLevel zapcore.LevelEncoder
EncodeTime zapcore.TimeEncoder
}
EncoderOption func(opts *encoderOptions)
)
func (opts *encoderOptions) IsOutputFormatConsole() bool {
if opts == nil {
return true
}
return opts.OutputFormat == OutputFormatConsole
}
func loadEncoderOptions(options ...EncoderOption) *encoderOptions {
opts := &encoderOptions{
OutputFormat: OutputFormatConsole,
MessagePrefix: "",
EncodeLevel: nil,
EncodeTime: nil,
}
for _, option := range options {
option(opts)
}
// EncodeLevel
if opts.EncodeLevel == nil {
if opts.IsOutputFormatConsole() {
// 大写 && 带颜色
opts.EncodeLevel = zapcore.CapitalColorLevelEncoder
} else {
// 大写
opts.EncodeLevel = zapcore.CapitalLevelEncoder
}
}
// EncodeTime
if opts.EncodeTime == nil {
if opts.IsOutputFormatConsole() {
opts.EncodeTime = zapcore.ISO8601TimeEncoder
} else {
opts.EncodeTime = zapcore.EpochTimeEncoder
}
}
return opts
}
func WithEncoderOutputFormatConsole() EncoderOption {
return func(opts *encoderOptions) {
opts.OutputFormat = OutputFormatConsole
}
}
func WithEncoderOutputFormatJson() EncoderOption {
return func(opts *encoderOptions) {
opts.OutputFormat = OutputFormatJson
}
}
func WithEncoderMessagePrefix(prefix string) EncoderOption {
return func(opts *encoderOptions) {
opts.MessagePrefix = prefix
}
}
func WithEncoderEncodeLevel(encodeLevel zapcore.LevelEncoder) EncoderOption {
return func(opts *encoderOptions) {
opts.EncodeLevel = encodeLevel
}
}
func WithEncoderEncodeTime(encodeTime zapcore.TimeEncoder) EncoderOption {
return func(opts *encoderOptions) {
opts.EncodeTime = encodeTime
}
}