/
main.go
87 lines (76 loc) · 2.35 KB
/
main.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
package main
import (
"fmt"
"os"
"time"
"github.com/natefinch/lumberjack"
"go.uber.org/zap"
"go.uber.org/zap/zapcore"
)
func syslogTimeEncoder(t time.Time, enc zapcore.PrimitiveArrayEncoder) {
enc.AppendString(fmt.Sprintf("|%s|", t.Format("2006-01-02T15:04:05")))
}
func filelogTimeEncoder(t time.Time, enc zapcore.PrimitiveArrayEncoder) {
enc.AppendString(fmt.Sprintf("%s", t.Format("2006-01-02T15:04:05")))
}
func customLevelEncoder(level zapcore.Level, enc zapcore.PrimitiveArrayEncoder) {
enc.AppendString(fmt.Sprintf("[%v]", level.CapitalString()))
}
func customEncodeCaller(caller zapcore.EntryCaller, enc zapcore.PrimitiveArrayEncoder) {
enc.AppendString(fmt.Sprintf("%d", caller.Line))
}
func main() {
terminalEncoder := zapcore.NewConsoleEncoder(zapcore.EncoderConfig{
MessageKey: "M",
LevelKey: "L",
TimeKey: "T",
NameKey: "N",
CallerKey: "C",
StacktraceKey: "S",
LineEnding: zapcore.DefaultLineEnding,
EncodeLevel: customLevelEncoder,
EncodeTime: syslogTimeEncoder,
EncodeDuration: zapcore.StringDurationEncoder,
EncodeCaller: zapcore.ShortCallerEncoder,
})
terminalOutput := zapcore.AddSync(os.Stderr)
fileEncoder := zapcore.NewJSONEncoder(zapcore.EncoderConfig{
MessageKey: "M",
LevelKey: "L",
TimeKey: "T",
NameKey: "N",
CallerKey: "C",
StacktraceKey: "S",
LineEnding: zapcore.DefaultLineEnding,
EncodeLevel: zapcore.CapitalLevelEncoder,
EncodeTime: filelogTimeEncoder,
EncodeDuration: zapcore.StringDurationEncoder,
EncodeCaller: zapcore.ShortCallerEncoder,
})
fileOutput := zapcore.AddSync(&lumberjack.Logger{
Filename: "logs.json",
MaxSize: 100, // megabytes
MaxBackups: 10,
MaxAge: 28, // days
Compress: true,
})
InfoLevel := zap.LevelEnablerFunc(func(lvl zapcore.Level) bool {
return lvl >= zapcore.InfoLevel
})
ErrorLevel := zap.LevelEnablerFunc(func(lvl zapcore.Level) bool {
return lvl >= zapcore.ErrorLevel
})
core2 := zapcore.NewTee(
zapcore.NewCore(terminalEncoder, terminalOutput, InfoLevel),
zapcore.NewCore(fileEncoder, fileOutput, ErrorLevel),
)
logger := zap.New(core2, zap.AddCaller(), zap.AddStacktrace(zapcore.ErrorLevel))
defer logger.Sync()
logger.Info("logger.info")
logger.Error("logger.Error ")
i := 0
for {
i++
logger.Error(fmt.Sprintf("logger.Error %d", i))
}
}