-
Notifications
You must be signed in to change notification settings - Fork 4
/
switcher.go
60 lines (49 loc) · 1.32 KB
/
switcher.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
package jsonlog
import (
"time"
)
var (
DAY_SWITCHER = daySwitch{} // 按天切换文件
HOURS_SWITCHER = hoursSwitch{} // 按小时切换文件
)
type Switcher interface {
FirstSwitchTime() time.Duration
NextSwitchTime() time.Duration
DirAndFileName(base string) (dir, file string)
}
type daySwitch struct{}
func (_ daySwitch) FirstSwitchTime() time.Duration {
// 到明天凌晨间隔多长时间
now := time.Now()
return time.Date(
now.Year(), now.Month(), now.Day(),
0, 0, 0, 0, now.Location(),
).Add(24 * time.Hour).Sub(now)
}
func (_ daySwitch) NextSwitchTime() time.Duration {
return 24 * time.Hour
}
func (_ daySwitch) DirAndFileName(base string) (dir, file string) {
now := time.Now()
dir = base + "/" + now.Format("2006-01/")
file = dir + now.Format("2006-01-02")
return
}
type hoursSwitch struct{}
func (_ hoursSwitch) FirstSwitchTime() time.Duration {
// 到下一个整点间隔多长时间
now := time.Now()
return time.Date(
now.Year(), now.Month(), now.Day(),
now.Hour(), 0, 0, 0, now.Location(),
).Add(time.Hour).Sub(now)
}
func (_ hoursSwitch) NextSwitchTime() time.Duration {
return time.Hour
}
func (_ hoursSwitch) DirAndFileName(base string) (dir, file string) {
now := time.Now()
dir = base + "/" + now.Format("2006-01/2006-01-02/")
file = dir + now.Format("2006-01-02_15")
return
}