-
Notifications
You must be signed in to change notification settings - Fork 1
/
log.go
363 lines (310 loc) · 8.39 KB
/
log.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
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
package echotool
import (
"io"
"os"
"runtime"
"time"
rl "github.com/lestrrat-go/file-rotatelogs"
"github.com/popeyeio/handy"
"github.com/songzhaoliang/echotool/json"
"go.uber.org/zap"
"go.uber.org/zap/zapcore"
)
var logger = NewDefaultLogger()
func NewDefaultLogger() *zap.SugaredLogger {
cfg := zap.Config{
Level: zap.NewAtomicLevelAt(zap.DebugLevel),
Encoding: "console",
EncoderConfig: NewDefaultEncodeConfig(),
OutputPaths: []string{"stdout"},
ErrorOutputPaths: []string{"stdout"},
}
l, _ := cfg.Build()
return l.Sugar()
}
// RotateConfig is the config for rotating logs.
// The format of suffix refers to https://github.com/lestrrat-go/strftime.
type RotateConfig struct {
EncoderConfig zapcore.EncoderConfig
Paths []string
Suffix string
Level zapcore.Level
RotateTime time.Duration
TTL time.Duration
}
type RotateConfigOption func(*RotateConfig)
func WithEncoderConfig(cfg zapcore.EncoderConfig) RotateConfigOption {
return func(c *RotateConfig) {
c.EncoderConfig = cfg
}
}
func WithPaths(paths []string) RotateConfigOption {
return func(c *RotateConfig) {
if len(paths) > 0 {
c.Paths = paths
}
}
}
func WithSuffix(suffix string) RotateConfigOption {
return func(c *RotateConfig) {
if !handy.IsEmptyStr(suffix) {
c.Suffix = suffix
}
}
}
func WithLevel(level zapcore.Level) RotateConfigOption {
return func(c *RotateConfig) {
c.Level = level
}
}
func WithRotateTime(t time.Duration) RotateConfigOption {
return func(c *RotateConfig) {
if t > 0 {
c.RotateTime = t
}
}
}
func WithTTL(ttl time.Duration) RotateConfigOption {
return func(c *RotateConfig) {
if ttl > 0 {
c.TTL = ttl
}
}
}
func NewRotateLogger(opts ...RotateConfigOption) (*zap.SugaredLogger, error) {
cfg := &RotateConfig{
EncoderConfig: NewDefaultEncodeConfig(),
Paths: []string{"stdout"},
Suffix: "%Y%m%d_%H",
Level: zapcore.DebugLevel,
RotateTime: time.Hour,
TTL: time.Hour * 24 * 7,
}
for _, opt := range opts {
opt(cfg)
}
level := zap.NewAtomicLevelAt(cfg.Level)
enc := zapcore.NewConsoleEncoder(cfg.EncoderConfig)
var cores []zapcore.Core
for _, path := range cfg.Paths {
switch path {
case "stdout":
cores = append(cores, zapcore.NewCore(enc, os.Stdout, level))
case "stderr":
cores = append(cores, zapcore.NewCore(enc, os.Stderr, level))
default:
w, err := rl.New(path+"."+cfg.Suffix,
rl.WithLinkName(path),
rl.WithRotationTime(cfg.RotateTime),
rl.WithMaxAge(cfg.TTL))
if err != nil {
return nil, err
}
cores = append(cores, zapcore.NewCore(enc, zapcore.AddSync(w), level))
}
}
return zap.New(zapcore.NewTee(cores...)).Sugar(), nil
}
func NewDefaultEncodeConfig() zapcore.EncoderConfig {
return zapcore.EncoderConfig{
TimeKey: "T",
LevelKey: "L",
NameKey: "N",
CallerKey: "C",
MessageKey: "M",
LineEnding: zapcore.DefaultLineEnding,
EncodeLevel: zapcore.CapitalLevelEncoder,
EncodeTime: func(t time.Time, enc zapcore.PrimitiveArrayEncoder) {
enc.AppendString(t.Format("2006-01-02 15:04:05"))
},
EncodeDuration: zapcore.StringDurationEncoder,
NewReflectedEncoder: FasterJSONReflectedEncoder,
}
}
func FasterJSONReflectedEncoder(w io.Writer) zapcore.ReflectedEncoder {
enc := json.NewEncoder(w)
enc.SetEscapeHTML(false)
return enc
}
func SetLogger(l *zap.SugaredLogger) {
if l != nil {
logger = l
}
}
func SetLoggerWithFinalizer(l *zap.SugaredLogger) {
if l != nil {
logger = l
runtime.SetFinalizer(l, func(l *zap.SugaredLogger) {
_ = l.Sync()
})
}
}
// FlushLog flushes any buffered log entries.
func FlushLog() error {
return logger.Sync()
}
func CtxDebug(ec *Context, format string, args ...interface{}) {
buildLogger(ec).Debugf(format, args...)
}
func CtxInfo(ec *Context, format string, args ...interface{}) {
buildLogger(ec).Infof(format, args...)
}
func CtxWarn(ec *Context, format string, args ...interface{}) {
buildLogger(ec).Warnf(format, args...)
}
func CtxError(ec *Context, format string, args ...interface{}) {
buildLogger(ec).Errorf(format, args...)
}
// CtxFatal logs a message, then calls os.Exit.
func CtxFatal(ec *Context, format string, args ...interface{}) {
buildLogger(ec).Fatalf(format, args...)
}
// CtxPanic logs a message, then panics.
func CtxPanic(ec *Context, format string, args ...interface{}) {
buildLogger(ec).Panicf(format, args...)
}
func CtxPrint(ec *Context, level zapcore.Level, format string, args ...interface{}) {
switch level {
case zapcore.DebugLevel:
CtxDebug(ec, format, args...)
case zapcore.InfoLevel:
CtxInfo(ec, format, args...)
case zapcore.WarnLevel:
CtxWarn(ec, format, args...)
case zapcore.ErrorLevel:
CtxError(ec, format, args...)
case zapcore.FatalLevel:
CtxFatal(ec, format, args...)
case zapcore.PanicLevel:
CtxPanic(ec, format, args...)
default:
CtxDebug(ec, format, args...)
}
}
func CtxDebugKV(ec *Context, msg string, fields ...zap.Field) {
buildLogger(ec).Desugar().Debug(msg, fields...)
}
func CtxInfoKV(ec *Context, msg string, fields ...zap.Field) {
buildLogger(ec).Desugar().Info(msg, fields...)
}
func CtxWarnKV(ec *Context, msg string, fields ...zap.Field) {
buildLogger(ec).Desugar().Warn(msg, fields...)
}
func CtxErrorKV(ec *Context, msg string, fields ...zap.Field) {
buildLogger(ec).Desugar().Error(msg, fields...)
}
// CtxFatalKV logs a message, then calls os.Exit.
func CtxFatalKV(ec *Context, msg string, fields ...zap.Field) {
buildLogger(ec).Desugar().Fatal(msg, fields...)
}
// CtxPanicKV logs a message, then panics.
func CtxPanicKV(ec *Context, msg string, fields ...zap.Field) {
buildLogger(ec).Desugar().Panic(msg, fields...)
}
func CtxPrintKV(ec *Context, level zapcore.Level, msg string, fields ...zap.Field) {
switch level {
case zapcore.DebugLevel:
CtxDebugKV(ec, msg, fields...)
case zapcore.InfoLevel:
CtxInfoKV(ec, msg, fields...)
case zapcore.WarnLevel:
CtxWarnKV(ec, msg, fields...)
case zapcore.ErrorLevel:
CtxErrorKV(ec, msg, fields...)
case zapcore.FatalLevel:
CtxFatalKV(ec, msg, fields...)
case zapcore.PanicLevel:
CtxPanicKV(ec, msg, fields...)
default:
CtxDebugKV(ec, msg, fields...)
}
}
func buildLogger(ec *Context) (l *zap.SugaredLogger) {
l = logger
if ec == nil {
return
}
if v := ec.GetNamedValue(); !handy.IsEmptyStr(v) {
l = l.Named(v)
}
for k, v := range ec.GetCustomValues() {
l = l.With(zap.String(k, v))
}
return
}
func Debug(format string, args ...interface{}) {
logger.Debugf(format, args...)
}
func Info(format string, args ...interface{}) {
logger.Infof(format, args...)
}
func Warn(format string, args ...interface{}) {
logger.Warnf(format, args...)
}
func Error(format string, args ...interface{}) {
logger.Errorf(format, args...)
}
// Fatal logs a message, then calls os.Exit.
func Fatal(format string, args ...interface{}) {
logger.Fatalf(format, args...)
}
// Panic logs a message, then panics.
func Panic(format string, args ...interface{}) {
logger.Panicf(format, args...)
}
func Print(level zapcore.Level, format string, args ...interface{}) {
switch level {
case zapcore.DebugLevel:
Debug(format, args...)
case zapcore.InfoLevel:
Info(format, args...)
case zapcore.WarnLevel:
Warn(format, args...)
case zapcore.ErrorLevel:
Error(format, args...)
case zapcore.FatalLevel:
Fatal(format, args...)
case zapcore.PanicLevel:
Panic(format, args...)
default:
Debug(format, args...)
}
}
func DebugKV(msg string, fields ...zap.Field) {
logger.Desugar().Debug(msg, fields...)
}
func InfoKV(msg string, fields ...zap.Field) {
logger.Desugar().Info(msg, fields...)
}
func WarnKV(msg string, fields ...zap.Field) {
logger.Desugar().Warn(msg, fields...)
}
func ErrorKV(msg string, fields ...zap.Field) {
logger.Desugar().Error(msg, fields...)
}
// FatalKV logs a message, then calls os.Exit.
func FatalKV(msg string, fields ...zap.Field) {
logger.Desugar().Fatal(msg, fields...)
}
// PanicKV logs a message, then panics.
func PanicKV(msg string, fields ...zap.Field) {
logger.Desugar().Panic(msg, fields...)
}
func PrintKV(level zapcore.Level, msg string, fields ...zap.Field) {
switch level {
case zapcore.DebugLevel:
DebugKV(msg, fields...)
case zapcore.InfoLevel:
InfoKV(msg, fields...)
case zapcore.WarnLevel:
WarnKV(msg, fields...)
case zapcore.ErrorLevel:
ErrorKV(msg, fields...)
case zapcore.FatalLevel:
FatalKV(msg, fields...)
case zapcore.PanicLevel:
PanicKV(msg, fields...)
default:
DebugKV(msg, fields...)
}
}