/
logger.go
229 lines (215 loc) · 5.98 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
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
package log
import (
"go.uber.org/zap"
"go.uber.org/zap/zapcore"
"gopkg.in/natefinch/lumberjack.v2"
"os"
"path/filepath"
"sync"
"time"
)
type Options struct {
// 日志文件保存位置
LogFileDir string
AppName string
ErrorFileName string
WarnFileName string
InfoFileName string
DebugFileName string
Level zapcore.Level
// 日志文件大小(MB)
MaxSize int
// 最多存在多少切片文件
MaxBackups int
// 保存的最大天数
MaxAge int
// 是否开启开发模式
Development bool
zap.Config
}
type ModOptions func(options *Options)
type Logger struct {
*zap.Logger
sync.RWMutex
Opts *Options `json:"opts"`
zapConfig zap.Config
initial bool
}
var (
l *Logger
sp = string(filepath.Separator)
errWS, warnWS, infoWS, debugWS zapcore.WriteSyncer // IO输出
debugConsoleWS = zapcore.Lock(os.Stdout) // 控制台标准输出
errorConsoleWS = zapcore.Lock(os.Stderr)
)
func NewLogger(mod ...ModOptions) *zap.Logger {
l = &Logger{}
l.Lock()
defer l.Unlock()
if l.initial {
l.Info("[Logger] logger Invited")
return nil
}
l.Opts = &Options{
LogFileDir: "",
AppName: "app_log",
ErrorFileName: "error.log",
WarnFileName: "warn.log",
InfoFileName: "info.log",
DebugFileName: "debug.log",
Level: zapcore.DebugLevel,
MaxSize: 100,
MaxBackups: 60,
MaxAge: 30,
}
if l.Opts.LogFileDir == "" {
l.Opts.LogFileDir, _ = filepath.Abs(filepath.Dir(filepath.Join(".")))
l.Opts.LogFileDir += sp + "logs" + sp
}
if l.Opts.Development {
l.zapConfig = zap.NewDevelopmentConfig()
l.zapConfig.EncoderConfig.EncodeTime = timeEncoder
} else {
l.zapConfig = zap.NewProductionConfig()
l.zapConfig.EncoderConfig.EncodeTime = timeUnixNano
}
if l.Opts.OutputPaths == nil || len(l.Opts.OutputPaths) == 0 {
l.zapConfig.OutputPaths = []string{"stdout"}
}
if l.Opts.ErrorOutputPaths == nil || len(l.Opts.ErrorOutputPaths) == 0 {
l.zapConfig.OutputPaths = []string{"stderr"}
}
for _, fn := range mod {
fn(l.Opts)
}
l.zapConfig.Level.SetLevel(l.Opts.Level)
l.init()
l.initial = true
l.Info("[Logger] success")
return l.Logger
}
func (l *Logger) init() {
l.setSyncers()
var err error
l.Logger, err = l.zapConfig.Build(l.cores())
if err != nil {
panic(err)
}
defer func(Logger *zap.Logger) {
_ = Logger.Sync()
}(l.Logger)
}
func (l *Logger) setSyncers() {
f := func(fN string) zapcore.WriteSyncer {
return zapcore.AddSync(&lumberjack.Logger{
Filename: l.Opts.LogFileDir + sp + l.Opts.AppName + "-" + fN,
MaxSize: l.Opts.MaxSize,
MaxBackups: l.Opts.MaxBackups,
MaxAge: l.Opts.MaxAge,
Compress: true,
LocalTime: true,
})
}
errWS = f(l.Opts.ErrorFileName)
warnWS = f(l.Opts.WarnFileName)
infoWS = f(l.Opts.InfoFileName)
debugWS = f(l.Opts.DebugFileName)
return
}
func SetMaxSize(MaxSize int) ModOptions {
return func(option *Options) {
option.MaxSize = MaxSize
}
}
func SetMaxBackups(MaxBackups int) ModOptions {
return func(option *Options) {
option.MaxBackups = MaxBackups
}
}
func SetMaxAge(MaxAge int) ModOptions {
return func(option *Options) {
option.MaxAge = MaxAge
}
}
func SetLogFileDir(LogFileDir string) ModOptions {
return func(option *Options) {
option.LogFileDir = LogFileDir
}
}
func SetAppName(AppName string) ModOptions {
return func(option *Options) {
option.AppName = AppName
}
}
func SetLevel(Level zapcore.Level) ModOptions {
return func(option *Options) {
option.Level = Level
}
}
func SetErrorFileName(ErrorFileName string) ModOptions {
return func(option *Options) {
option.ErrorFileName = ErrorFileName
}
}
func SetWarnFileName(WarnFileName string) ModOptions {
return func(option *Options) {
option.WarnFileName = WarnFileName
}
}
func SetInfoFileName(InfoFileName string) ModOptions {
return func(option *Options) {
option.InfoFileName = InfoFileName
}
}
func SetDebugFileName(DebugFileName string) ModOptions {
return func(option *Options) {
option.DebugFileName = DebugFileName
}
}
func SetDevelopment(Development bool) ModOptions {
return func(option *Options) {
option.Development = Development
}
}
func (l *Logger) cores() zap.Option {
fileEncoder := zapcore.NewJSONEncoder(l.zapConfig.EncoderConfig)
encoderConfig := zap.NewDevelopmentEncoderConfig()
encoderConfig.EncodeTime = timeEncoder
encoderConfig.EncodeLevel = zapcore.CapitalColorLevelEncoder
consoleEncoder := zapcore.NewConsoleEncoder(encoderConfig)
errPriority := zap.LevelEnablerFunc(func(lvl zapcore.Level) bool {
return lvl == zapcore.ErrorLevel && zapcore.ErrorLevel-l.zapConfig.Level.Level() > -1
})
warnPriority := zap.LevelEnablerFunc(func(lvl zapcore.Level) bool {
return lvl == zapcore.WarnLevel && zapcore.WarnLevel-l.zapConfig.Level.Level() > -1
})
infoPriority := zap.LevelEnablerFunc(func(lvl zapcore.Level) bool {
return lvl == zapcore.InfoLevel && zapcore.InfoLevel-l.zapConfig.Level.Level() > -1
})
debugPriority := zap.LevelEnablerFunc(func(lvl zapcore.Level) bool {
return lvl == zapcore.DebugLevel && zapcore.DebugLevel-l.zapConfig.Level.Level() > -1
})
cores := []zapcore.Core{
zapcore.NewCore(fileEncoder, errWS, errPriority),
zapcore.NewCore(fileEncoder, warnWS, warnPriority),
zapcore.NewCore(fileEncoder, infoWS, infoPriority),
zapcore.NewCore(fileEncoder, debugWS, debugPriority),
}
if l.Opts.Development {
cores = append(cores, []zapcore.Core{
zapcore.NewCore(consoleEncoder, errorConsoleWS, errPriority),
zapcore.NewCore(consoleEncoder, debugConsoleWS, warnPriority),
zapcore.NewCore(consoleEncoder, debugConsoleWS, infoPriority),
zapcore.NewCore(consoleEncoder, debugConsoleWS, debugPriority),
}...)
}
return zap.WrapCore(func(c zapcore.Core) zapcore.Core {
return zapcore.NewTee(cores...)
})
}
func timeEncoder(t time.Time, enc zapcore.PrimitiveArrayEncoder) {
enc.AppendString(t.Format("2006-01-02 15:04:05"))
}
func timeUnixNano(t time.Time, enc zapcore.PrimitiveArrayEncoder) {
enc.AppendInt64(t.UnixNano() / 1e6)
}