/
opt.go
84 lines (69 loc) · 1.49 KB
/
opt.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
package logger
import (
"context"
"os"
"go.uber.org/zap"
"go.uber.org/zap/zapcore"
)
const (
defaultTraceLoggerName = "trace_id"
defaultSpanLoggerName = "span_id"
)
type CtxOption interface {
apply(config) config
}
type optionFunc func(config) config
func (fn optionFunc) apply(cfg config) config {
return fn(cfg)
}
type Trace struct {
TraceID string
SpanID string
}
type ExtractTrace func(ctx context.Context) Trace
type config struct {
enabledTrace bool
traceKey string
spanKey string
parseTrace ExtractTrace
core zapcore.Core
opts []zap.Option
}
func newDefaultConfig() config {
return config{
traceKey: defaultTraceLoggerName,
spanKey: defaultSpanLoggerName,
core: zapcore.NewCore(zapcore.NewJSONEncoder(zapcore.EncoderConfig{MessageKey: "message"}), os.Stdout, zap.DebugLevel),
}
}
func EnableTrace() CtxOption {
return optionFunc(func(cfg config) config {
cfg.enabledTrace = true
return cfg
})
}
func WithZapCore(core zapcore.Core) CtxOption {
return optionFunc(func(cfg config) config {
cfg.core = core
return cfg
})
}
func WithZapOpts(opts ...zap.Option) CtxOption {
return optionFunc(func(cfg config) config {
cfg.opts = opts
return cfg
})
}
func WithTraceKey(tn string, sn string) CtxOption {
return optionFunc(func(cfg config) config {
cfg.traceKey = tn
cfg.spanKey = sn
return cfg
})
}
func WithParseTrace(f ExtractTrace) CtxOption {
return optionFunc(func(cfg config) config {
cfg.parseTrace = f
return cfg
})
}