-
Notifications
You must be signed in to change notification settings - Fork 0
/
tracer.go
75 lines (59 loc) · 1.35 KB
/
tracer.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
package log
import (
"io"
"time"
"github.com/uber-go/zap"
)
const (
dateFormat = "2006-01-02T15:04:05.999999Z07:00"
)
// Tracer contains the root of the logging structure
type Tracer struct {
logger zap.Logger
level zap.AtomicLevel
}
func (t *Tracer) Debug() {
t.level.SetLevel(zap.DebugLevel)
}
type timestamp struct {
format string
}
func (t *timestamp) String() string {
return time.Now().UTC().Format(t.format)
}
type config struct {
encoder zap.Encoder
options []zap.Option
}
type Option func(*config)
// NewTracer constructs a new tracer that logs to the specified writer
func NewTracer(out io.Writer, opts ...Option) *Tracer {
var w zap.WriteSyncer
if v, ok := out.(zap.WriteSyncer); ok {
w = v
} else {
w = zap.AddSync(out)
}
skipField := zap.Skip()
noLevel := zap.LevelFormatter(func(zap.Level) zap.Field { return skipField })
c := &config{
encoder: zap.NewJSONEncoder(zap.NoTime(), noLevel),
options: []zap.Option{
zap.Fields(zap.Stringer("timestamp", ×tamp{format: dateFormat})),
},
}
for _, opt := range opts {
opt(c)
}
atomicLevel := zap.DynamicLevel()
return &Tracer{
logger: zap.New(c.encoder, append(c.options, zap.Output(w), atomicLevel)...),
level: atomicLevel,
}
}
func Text() Option {
return func(c *config) {
c.encoder = zap.NewTextEncoder(zap.TextNoTime())
c.options = []zap.Option{}
}
}