-
Notifications
You must be signed in to change notification settings - Fork 1
/
logger.go
61 lines (55 loc) · 1.62 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
package main
import (
"path"
"time"
rotatelogs "github.com/lestrrat/go-file-rotatelogs"
"github.com/rifflock/lfshook"
"github.com/sirupsen/logrus"
)
var logger *logrus.Entry
type ServerLogger struct {
maxAge time.Duration
rotationTime time.Duration
logPath string
logFileName string
contextLogger *logrus.Logger
}
func (s *ServerLogger) configureLogToLocal() {
s.contextLogger = logrus.New()
baseLogPath := path.Join(s.logPath, s.logFileName)
writer, err := rotatelogs.New(
baseLogPath+".%Y%m%d",
rotatelogs.WithLinkName(baseLogPath), // 生成软链,指向最新日志文件
rotatelogs.WithMaxAge(s.maxAge), // 文件最大保存时间
rotatelogs.WithRotationTime(s.rotationTime), // 日志切割时间间隔
)
if err != nil {
logrus.Fatalf("[Flight-Go]配置日志本地化操作失败, 错误原因: %v", err)
}
lfHook := lfshook.NewHook(lfshook.WriterMap{
logrus.DebugLevel: writer,
logrus.InfoLevel: writer,
logrus.WarnLevel: writer,
logrus.ErrorLevel: writer,
logrus.FatalLevel: writer,
logrus.PanicLevel: writer,
}, &logrus.TextFormatter{
TimestampFormat: "2006-01-02 15:04:05",
DisableTimestamp: false,
})
s.contextLogger.AddHook(lfHook)
}
func NewLogger(maxAge, rotationTime time.Duration, logPath, logFileName string) *logrus.Entry {
newLogger := &ServerLogger{
maxAge: maxAge,
rotationTime: rotationTime,
logPath: logPath,
logFileName: logFileName,
}
newLogger.configureLogToLocal()
logger = newLogger.contextLogger.WithFields(logrus.Fields{
"serviceName": serviceName,
"version": currentServiceVersion,
})
return logger
}