-
Notifications
You must be signed in to change notification settings - Fork 3
/
writeCloser_spec.go
67 lines (59 loc) · 1.76 KB
/
writeCloser_spec.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
package ioKit
import (
"fmt"
"github.com/richelieu-yang/chimera/v2/src/consts"
"github.com/richelieu-yang/chimera/v2/src/core/strKit"
"github.com/richelieu-yang/chimera/v2/src/cronKit"
"github.com/robfig/cron/v3"
"github.com/sirupsen/logrus"
"io"
"math"
)
type DailyWriteCloser struct {
writeCloser io.WriteCloser
cron *cron.Cron
}
func (dwc *DailyWriteCloser) Write(p []byte) (int, error) {
return dwc.writeCloser.Write(p)
}
func (dwc *DailyWriteCloser) Close() error {
_ = dwc.cron.Stop()
return dwc.writeCloser.Close()
}
// NewDailyWriteCloser 每天凌晨0点,执行Rotate().
/*
@param options 可选配置,参考 NewLumberJackWriteCloser()
*/
func NewDailyWriteCloser(filePath string, options ...LumberJackOption) (io.WriteCloser, error) {
return NewRotatableWriteCloserWithSpec(filePath, "0 0 0 * * *", options...)
}
// NewRotatableWriteCloserWithSpec 满足条件(spec),执行Rotate().
/*
PS:
(1) 可能存在情况,Rotate()后,生成的旧日志文件大小为0B.
*/
func NewRotatableWriteCloserWithSpec(filePath string, spec string, options ...LumberJackOption) (io.WriteCloser, error) {
// math.MaxInt64: 8.0 EiB
wc, err := NewLumberJackWriteCloser(filePath, math.MaxInt64, options...)
if err != nil {
return nil, err
}
c, _, err := cronKit.NewCronWithTask(spec, func() {
text := fmt.Sprintf("[%s] Rotate by cron.\n", strKit.ToUpper(consts.ProjectName))
_, _ = wc.Write([]byte(text))
if err := wc.Rotate(); err != nil {
text := fmt.Sprintf("[%s] Fail to rotate by cron, error:\n%v\n", strKit.ToUpper(consts.ProjectName), err)
_, _ = wc.Write([]byte(text))
logrus.Error(text)
}
})
if err != nil {
return nil, err
}
// Start() 不阻塞
c.Start()
return &DailyWriteCloser{
writeCloser: wc,
cron: c,
}, nil
}