generated from logur/integration-template
-
Notifications
You must be signed in to change notification settings - Fork 0
/
logger.go
93 lines (72 loc) · 1.96 KB
/
logger.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
85
86
87
88
89
90
91
92
93
// Package zap provides Logur integration for Uber's Zap.
package zap
import (
"fmt"
"go.uber.org/zap"
"go.uber.org/zap/zapcore"
"logur.dev/logur"
)
// New returns a new Zap logger.
func New(logger logur.Logger) *zap.Logger {
z := &zapper{
logger: logger,
}
if levelEnabler, ok := logger.(logur.LevelEnabler); ok {
z.levelEnabler = levelEnabler
}
return zap.New(z)
}
// zapper is created based on github.com/uber-common/bark/zbark.zapper.
type zapper struct {
logger logur.Logger
levelEnabler logur.LevelEnabler
}
func (z *zapper) Enabled(lvl zapcore.Level) bool {
if z.levelEnabler == nil {
return true
}
// Logur does not have fatal and panic levels,
// but since they are above error in severity, we fall back to error
if lvl > zapcore.ErrorLevel {
lvl = zapcore.ErrorLevel
}
return z.levelEnabler.LevelEnabled(logur.Level(lvl + 2))
}
func (z *zapper) With(fs []zapcore.Field) zapcore.Core {
me := zapcore.NewMapObjectEncoder()
for _, f := range fs {
f.AddTo(me)
}
return &zapper{logur.WithFields(z.logger, me.Fields), z.levelEnabler}
}
func (z *zapper) Check(ent zapcore.Entry, ce *zapcore.CheckedEntry) *zapcore.CheckedEntry {
if z.Enabled(ent.Level) {
return ce.AddCore(ent, z)
}
return ce
}
func (z *zapper) Write(ent zapcore.Entry, fs []zapcore.Field) error {
me := zapcore.NewMapObjectEncoder()
for _, f := range fs {
f.AddTo(me)
}
var logFunc func(string, ...map[string]interface{})
switch ent.Level {
case zapcore.DebugLevel:
logFunc = z.logger.Debug
case zapcore.InfoLevel:
logFunc = z.logger.Info
case zapcore.WarnLevel:
logFunc = z.logger.Warn
case zapcore.ErrorLevel, zapcore.DPanicLevel, zapcore.PanicLevel, zapcore.FatalLevel:
logFunc = z.logger.Error
default:
return fmt.Errorf("logur-to-zap compatibility wrapper got unknown level %v", ent.Level)
}
logFunc(ent.Message, me.Fields)
return nil
}
func (z *zapper) Sync() error {
// Logur doesn't expose a way to flush buffered messages.
return nil
}