/
options.go
81 lines (65 loc) · 1.46 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
package log
import (
"fmt"
"github.com/pkg/errors"
"go.uber.org/zap/zapcore"
)
// Option configures a logger.
type Option interface {
apply(c *config) error
}
type optionFunc func(c *config) error
func (fn optionFunc) apply(c *config) error {
return fn(c)
}
// Preset turns a list of Option instances into an Option
func Preset(options ...Option) Option {
return optionFunc(func(c *config) error {
for _, option := range options {
if err := option.apply(c); err != nil {
return errors.Wrap(err, "failed to apply option")
}
}
return nil
})
}
func SetLevel(level string) Option {
return optionFunc(func(c *config) error {
if level == "" {
c.level = defaultLevel
return nil
}
lvl, err := zapcore.ParseLevel(level)
if err != nil {
return errors.Wrap(err, "failed to parse logger level")
}
c.level = lvl
return nil
})
}
func SetMode(mode string) Option {
return optionFunc(func(c *config) error {
if mode == "" {
c.mode = defaultMode
return nil
}
if mode != developmentMode && mode != productionMode {
return fmt.Errorf("unknown logger mode %q", mode)
}
c.mode = mode
return nil
})
}
func SetEncoding(encoding string) Option {
return optionFunc(func(c *config) error {
if encoding == "" {
c.encoding = defaultEncoding
return nil
}
if encoding != consoleEncoding && encoding != jsonEncoding {
return fmt.Errorf("unknown logger encoding %q", encoding)
}
c.encoding = encoding
return nil
})
}