-
Notifications
You must be signed in to change notification settings - Fork 6
/
Copy pathlog_hooks.go
47 lines (42 loc) · 987 Bytes
/
log_hooks.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
package kuu
import (
"fmt"
"github.com/sirupsen/logrus"
"os"
"path"
"time"
)
// LogDailyFileHook
type LogDailyFileHook struct{}
// Levels
func (h *LogDailyFileHook) Levels() []logrus.Level {
return logrus.AllLevels
}
// Fire
func (h *LogDailyFileHook) Fire(entry *logrus.Entry) error {
now := fmt.Sprintf("kuu-%s.log", time.Now().Format("2006-01-02"))
if now != DailyFileName || DailyFile == nil {
DailyFileName = now
changeLoggerOutput(now)
}
// 输出到控制台
logrus.StandardLogger().WithFields(entry.Data).Log(entry.Level, entry.Message)
return nil
}
func changeLoggerOutput(filePath string) {
if LogDir == "" {
return
}
EnsureDir(LogDir)
filePath = path.Join(LogDir, filePath)
file, err := os.OpenFile(filePath, os.O_CREATE|os.O_WRONLY|os.O_APPEND, 0666)
if err == nil {
Logger.Out = file
if DailyFile != nil {
_ = DailyFile.Close()
}
DailyFile = file
} else {
ERROR("创建日志文件失败,使用标准输出流输出日志")
}
}