-
Notifications
You must be signed in to change notification settings - Fork 17
/
日志类.go
91 lines (81 loc) · 2.79 KB
/
日志类.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
// Package elog 日志模块
package elog
import (
"go.uber.org/zap"
"go.uber.org/zap/zapcore"
"gopkg.in/natefinch/lumberjack.v2"
"os"
)
type E日志类 struct {
Logger *zap.SugaredLogger
LoggerObj *zap.Logger
}
func New日志类(日志文件路径 string, 日志级别 string) *E日志类 {
var log E日志类
v := log.E初始化(日志文件路径, 日志级别)
return v
}
func (this *E日志类) E初始化(日志文件路径 string, 日志级别 string) *E日志类 {
hook := lumberjack.Logger{
Filename: 日志文件路径, // ⽇志⽂件路径
MaxSize: 1024, // megabytes
MaxBackups: 3, // 最多保留3个备份
MaxAge: 365, //days
Compress: true, // 是否压缩 disabled by default
}
fileWriter := zapcore.AddSync(&hook)
var highPriority zapcore.Level
switch 日志级别 {
case "debug":
highPriority = zap.DebugLevel
case "info":
highPriority = zap.InfoLevel
case "error":
highPriority = zap.ErrorLevel
default:
highPriority = zap.InfoLevel
}
//配置日志的格式
encoderConfig := zap.NewProductionEncoderConfig()
encoderConfig.EncodeTime = zapcore.ISO8601TimeEncoder
encoderConfig.TimeKey = "time"
encoderConfig.EncodeLevel = zapcore.CapitalLevelEncoder
encoderConfig.EncodeDuration = zapcore.SecondsDurationEncoder
encoderConfig.EncodeCaller = zapcore.ShortCallerEncoder
encoderConfig.CallerKey = "caller"
consoleEncoder := zapcore.NewJSONEncoder(encoderConfig)
//consoleEncoder := zapcore.NewConsoleEncoder(zap.NewDevelopmentEncoderConfig())
consoleDebugging := zapcore.Lock(os.Stdout)
lowPriority := zap.LevelEnablerFunc(func(lvl zapcore.Level) bool {
return lvl >= zapcore.DebugLevel
})
core := zapcore.NewTee(
// 打印在控制台
zapcore.NewCore(consoleEncoder, consoleDebugging, lowPriority),
// 打印在文件中
zapcore.NewCore(consoleEncoder, fileWriter, highPriority),
)
//代码的位置也可以输出
//Logger := zap.New(core, zap.AddCaller(), zap.AddCallerSkip(1))
this.LoggerObj = zap.New(core, zap.AddCaller(), zap.AddCallerSkip(1), zap.AddStacktrace(zapcore.WarnLevel))
this.Logger = this.LoggerObj.Sugar()
// 替换全局log
zap.ReplaceGlobals(this.LoggerObj)
return this
}
func (this *E日志类) Log(msg string, keysAndValues ...interface{}) {
//this.Logger.Info(msg, fields...)
this.Logger.Infow(msg, keysAndValues...)
}
func (this *E日志类) E错误日志(msg string, keysAndValues ...interface{}) {
//this.Logger.Info(msg, fields...)
this.Logger.Errorw(msg, keysAndValues...)
}
func (this *E日志类) E警告日志(msg string, keysAndValues ...interface{}) {
//this.Logger.Info(msg, fields...)
this.Logger.Warnw(msg, keysAndValues...)
}
func (this *E日志类) E信息日志(msg string, keysAndValues ...interface{}) {
//this.Logger.Info(msg, fields...)
this.Logger.Infow(msg, keysAndValues...)
}