/
options.go
107 lines (90 loc) · 2.3 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
package log
import (
"io"
)
type LoggerType int
const (
ZapLogger LoggerType = iota
)
type Options struct {
Writer io.Writer
ErrWriter io.Writer
Fields map[string]interface{}
LevelEnabler Level
AddStack Level
AddCaller bool
CallerSkip int
EncoderCfg EncoderConfig
Encoder Encoder
OnFatal any
}
type Option interface {
apply(*Options)
}
type optionFunc func(*Options)
func (f optionFunc) apply(opts *Options) {
f(opts)
}
// LevelEnabler decides whether a given logging level is enabled when logging a
// message.
func WithLevelEnabler(lvl Level) Option {
return optionFunc(func(opts *Options) {
opts.LevelEnabler = lvl
})
}
func WithWriter(writer io.Writer) Option {
return optionFunc(func(opts *Options) {
opts.Writer = writer
})
}
// AddCaller configures the Logger to annotate each message with the filename
// and line number of logger's caller.
func AddCaller() Option {
return optionFunc(func(opts *Options) {
opts.AddCaller = true
})
}
// AddCallerSkip increases the number of callers skipped by caller annotation
// (as enabled by the AddCaller option).
func AddCallerSkip(skip int) Option {
return optionFunc(func(opts *Options) {
opts.CallerSkip += skip
})
}
// AddStacktrace configures the Logger to record a stack trace for all messages at
// or above a given level.
func AddStacktrace(lvl Level) Option {
return optionFunc(func(opts *Options) {
opts.AddStack = lvl
})
}
// Fields adds fields to the Logger.
func Fields(fs map[string]interface{}) Option {
return optionFunc(func(opts *Options) {
opts.Fields = fs
})
}
// ErrorOutput sets the destination for errors generated by the Logger. Note
// that this option only affects internal errors; for sample code that sends
// error-level logs to a different location from info- and debug-level logs,
// see the package-level AdvancedConfiguration example.
func ErrorOutput(w io.Writer) Option {
return optionFunc(func(opts *Options) {
opts.ErrWriter = w
})
}
func WithEncoderCfg(cfg EncoderConfig) Option {
return optionFunc(func(opts *Options) {
opts.EncoderCfg = cfg
})
}
func WithEncoder(encoder Encoder) Option {
return optionFunc(func(opts *Options) {
opts.Encoder = encoder
})
}
func WithOnFatal(onFatal any) Option {
return optionFunc(func(o *Options) {
o.OnFatal = onFatal
})
}