-
Notifications
You must be signed in to change notification settings - Fork 0
/
option.go
78 lines (65 loc) · 1.35 KB
/
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
package logging
import (
"io"
"log/slog"
"os"
"time"
)
type Option interface {
apply(opt *option)
}
type optionFn func(opt *option)
func (fn optionFn) apply(opt *option) {
fn(opt)
}
type ReplaceAttr func(groups []string, a slog.Attr) slog.Attr
type option struct {
writer io.Writer
level slog.Leveler
handler slog.Handler
replaceAttr ReplaceAttr
}
func defaultReplaceAttr(groups []string, a slog.Attr) slog.Attr {
if a.Key == "time" {
return slog.String(a.Key, time.Now().Format(time.RFC3339))
}
return a
}
var (
defaultOption = &option{
writer: os.Stdout,
level: slog.LevelInfo,
handler: slog.NewJSONHandler(os.Stdout, &slog.HandlerOptions{
Level: slog.LevelInfo,
ReplaceAttr: defaultReplaceAttr,
}),
replaceAttr: defaultReplaceAttr,
}
)
func defaultOptions(opts ...Option) *option {
o := *defaultOption
for _, opt := range opts {
opt.apply(&o)
}
return &o
}
func WithWriter(writer io.Writer) Option {
return optionFn(func(opt *option) {
opt.writer = writer
})
}
func WithLevel(level slog.Leveler) Option {
return optionFn(func(opt *option) {
opt.level = level
})
}
func WithHandler(handler slog.Handler) Option {
return optionFn(func(opt *option) {
opt.handler = handler
})
}
func WithReplaceAttr(attrFn ReplaceAttr) Option {
return optionFn(func(opt *option) {
opt.replaceAttr = attrFn
})
}