-
Notifications
You must be signed in to change notification settings - Fork 0
/
handler.go
83 lines (70 loc) · 1.7 KB
/
handler.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
package slogx
import (
"context"
"io"
"go.uber.org/zap"
"go.uber.org/zap/zapcore"
"golang.org/x/exp/slog"
)
var _ slog.Handler = (*Handler)(nil)
type HandlerOptions struct {
Level slog.Leveler
Prefix string
AddSource bool
AddCaller bool
AddStackTrace bool
ReplaceAttr func(groups []string, a slog.Attr) slog.Attr
}
type Handler struct {
opts HandlerOptions // 控制写什么
e Encoder // 控制怎么写
w io.Writer // 控制往那写
group string
core slog.Handler
}
func NewHandler(w io.Writer, opts *HandlerOptions) *Handler {
if opts == nil {
opts = &HandlerOptions{}
}
return opts.NewHandler(w)
}
func (opts HandlerOptions) NewHandler(w io.Writer) *Handler {
return &Handler{
opts: opts,
w: w,
core: slog.HandlerOptions{
AddSource: opts.AddSource,
Level: opts.Level,
ReplaceAttr: opts.ReplaceAttr,
}.NewJSONHandler(w),
}
}
func (h *Handler) Enabled(ctx context.Context, level slog.Level) bool {
return h.core.Enabled(ctx, level)
}
func (h *Handler) Handle(ctx context.Context, record slog.Record) error {
return h.core.Handle(ctx, record)
}
func (h *Handler) WithAttrs(attrs []slog.Attr) slog.Handler {
return &Handler{
opts: h.opts,
e: h.e,
w: h.w,
core: h.core.WithAttrs(attrs),
}
}
func (h *Handler) WithGroup(name string) slog.Handler {
return &Handler{
opts: h.opts,
e: h.e,
w: h.w,
group: name,
core: h.core.WithGroup(name),
}
}
func getEncoder() zapcore.Encoder {
encoderConfig := zap.NewProductionEncoderConfig()
encoderConfig.EncodeTime = zapcore.ISO8601TimeEncoder
encoderConfig.EncodeLevel = zapcore.CapitalLevelEncoder
return zapcore.NewConsoleEncoder(encoderConfig)
}