-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathrotation.go
More file actions
49 lines (40 loc) · 1.03 KB
/
Copy pathrotation.go
File metadata and controls
49 lines (40 loc) · 1.03 KB
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
package log
import (
"fmt"
"os"
"strings"
"sync"
"time"
)
var registerLogPaths sync.Map
func timeToLogFile() {
registerLogPaths.Range(func(l, _ any) bool {
logPath := strings.TrimSuffix(l.(string), ".log")
os.RemoveAll(logPath + ".log")
os.Symlink(fmt.Sprintf("%s-%s.log", logPath, time.Now().Format("2006-01-02")), logPath+".log")
return true
})
}
func scheduleLogRotation() {
for {
now := time.Now()
// 计算明天的时间
next := now.Add(24 * time.Hour)
next = time.Date(next.Year(), next.Month(), next.Day(), 0, 1, 0, 0, next.Location()) // 设置为第二天的 00:01:00
// 如果当前时间已经过了今天的00:01,则等待到明天
if next.Before(now) {
next = next.Add(24 * time.Hour)
}
duration := next.Sub(now)
// fmt.Printf("下次日志轮转时间: %v\n", next.Format("2006-01-02 15:04:05"))
// 等待到设定时间
time.Sleep(duration)
// 执行日志文件切换
timeToLogFile()
}
}
// 启动日志轮转
func StartLogRotation() {
timeToLogFile()
go scheduleLogRotation()
}