-
Notifications
You must be signed in to change notification settings - Fork 3
/
rotate.go
64 lines (59 loc) · 1.93 KB
/
rotate.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
package consoleKit
import (
"fmt"
"github.com/richelieu-yang/chimera/v2/src/consts"
"github.com/richelieu-yang/chimera/v2/src/core/fileKit"
"github.com/richelieu-yang/chimera/v2/src/core/pathKit"
"github.com/richelieu-yang/chimera/v2/src/core/strKit"
"github.com/richelieu-yang/chimera/v2/src/core/timeKit"
"github.com/richelieu-yang/chimera/v2/src/cronKit"
"github.com/robfig/cron/v3"
"github.com/sirupsen/logrus"
"time"
)
// RotateOutput spec触发时,备份并清空传参output对应的文件.
/*
PS:
(1) 缺陷: 可能会丢部分输出,目前没啥好的办法解决.
(2) 建议每天一次.
(3) 不能将nohup.out重命名然后再新建个nohup.out,因为输出还是会到原先那个nohup.out中.
@param output 控制台输出文件(e.g.nohup.out)的路径
@param backDir 备份文件存放的目录
*/
func RotateOutput(output, backupDir, spec string) (*cron.Cron, error) {
c, _, err := cronKit.NewCronWithTask(spec, func() {
if backupPath, err := rotate(output, backupDir); err != nil {
logrus.WithError(err).Errorf("[%s] Fail to rotate.", strKit.ToUpper(consts.ProjectName))
} else {
logrus.WithFields(logrus.Fields{
"backupPath": backupPath,
}).Infof("[%s] Succeed to rotate.", strKit.ToUpper(consts.ProjectName))
}
})
if err != nil {
return nil, err
}
c.Start()
return c, nil
}
func rotate(output, backupDir string) (string, error) {
if err := fileKit.AssertExistAndIsFile(output); err != nil {
return "", err
}
if err := fileKit.MkDirs(backupDir); err != nil {
return "", err
}
dateStr := timeKit.Format(time.Now().Add(-timeKit.Day), "2006-01-02")
name := fileKit.GetName(output)
ext := fileKit.GetExt(output)
target := pathKit.Join(backupDir, fmt.Sprintf("%s-%s%s", name, dateStr, ext))
// 复制文件
if err := fileKit.CopyFile(output, target); err != nil {
return "", err
}
// 清空文件
if err := fileKit.Truncate(output, 0); err != nil {
return "", err
}
return target, nil
}