-
Notifications
You must be signed in to change notification settings - Fork 462
/
zap.go
52 lines (44 loc) · 1.34 KB
/
zap.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
package journal
import (
"go.uber.org/zap"
"go.uber.org/zap/zapcore"
)
// NewZapJournal returns a Journal backed by a zap logger. ZapJournal writes entries as ndjson to
// file at `filepath`.
func NewZapJournal(filepath string) (Journal, error) {
zapCfg := zap.NewProductionConfig()
zapCfg.Encoding = "json"
zapCfg.EncoderConfig.EncodeTime = zapcore.ISO8601TimeEncoder
zapCfg.EncoderConfig.LevelKey = ""
zapCfg.EncoderConfig.CallerKey = ""
zapCfg.EncoderConfig.MessageKey = "_event"
zapCfg.EncoderConfig.NameKey = "_topic"
zapCfg.OutputPaths = []string{filepath}
zapCfg.ErrorOutputPaths = []string{"stderr"}
global, err := zapCfg.Build()
if err != nil {
return nil, err
}
return &ZapJournal{global}, nil
}
// ZapJournal implemented the Journal interface.
type ZapJournal struct {
logger *zap.Logger
}
// Topic returns a Writer that records events for a topic.
func (zj *ZapJournal) Topic(topic string) Writer {
return &ZapWriter{
logger: zj.logger.Sugar().Named(topic),
topic: topic,
}
}
// ZapWriter implements the Journal Write interface and is backed by a zap logger.
type ZapWriter struct {
logger *zap.SugaredLogger
topic string
}
// Write records an operation and its metadata to a Journal accepting variadic key-value
// pairs.
func (zw *ZapWriter) Write(event string, kvs ...interface{}) {
zw.logger.Infow(event, kvs...)
}