/
zap.go
96 lines (82 loc) · 2.04 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
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
94
95
96
package abslog
import (
"fmt"
"go.uber.org/zap"
"go.uber.org/zap/zapcore"
"os"
"time"
)
const logTimeFormat = "2006-01-02T15:04:05Z"
func getZapLogger(logLevel LogLevel, encoder EncoderType) AbsLog {
// Encoder config
cfg := zapcore.EncoderConfig{
MessageKey: "message",
LevelKey: "severity",
EncodeLevel: zapcore.CapitalLevelEncoder,
TimeKey: "timestamp",
EncodeTime: customTimeEncoder,
CallerKey: "caller",
EncodeCaller: zapcore.ShortCallerEncoder,
StacktraceKey: "trace",
}
var enc zapcore.Encoder
switch encoder {
case ConsoleEncoder:
enc = zapcore.NewConsoleEncoder(cfg)
case JSONEncoder:
enc = zapcore.NewJSONEncoder(cfg)
default:
panic(fmt.Sprintf("Encoder type '%v' is not supported", encoder))
}
// Get ZapCore equivalent of log level
zapLevel := getZapLevel(logLevel)
// Stdout level enabler
stdoutLevels := zap.LevelEnablerFunc(func(level zapcore.Level) bool {
return level >= zapLevel && level < zap.ErrorLevel
})
// Stderr level enabler
stderrLevels := zap.LevelEnablerFunc(func(level zapcore.Level) bool {
return level >= zap.ErrorLevel && level >= zapLevel
})
// Write syncers
stdoutSyncer := zapcore.Lock(os.Stdout)
stderrSyncer := zapcore.Lock(os.Stderr)
// Core multi-output
core := zapcore.NewTee(
zapcore.NewCore(
enc,
stdoutSyncer,
stdoutLevels,
),
zapcore.NewCore(
enc,
stderrSyncer,
stderrLevels,
),
)
// Create logger
logger := zap.New(core, zap.AddCaller(), zap.AddCallerSkip(1), zap.AddStacktrace(zap.ErrorLevel))
sugar := logger.Sugar()
return &alterAbsLog{sugar}
}
func customTimeEncoder(t time.Time, enc zapcore.PrimitiveArrayEncoder) {
enc.AppendString(t.Format(logTimeFormat))
}
func getZapLevel(logLevel LogLevel) zapcore.Level {
switch logLevel {
case DebugLevel:
return zap.DebugLevel
case InfoLevel:
return zap.InfoLevel
case WarnLevel:
return zap.WarnLevel
case ErrorLevel:
return zap.ErrorLevel
case PanicLevel:
return zap.PanicLevel
case FatalLevel:
return zap.FatalLevel
default:
return zap.InfoLevel
}
}