-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathoutput.go
107 lines (93 loc) · 2.01 KB
/
output.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
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
package log
import (
"fmt"
"github.com/elliotchance/pie/v2"
"io"
"os"
"path/filepath"
"time"
rotatelogs "github.com/lestrrat-go/file-rotatelogs"
)
func SetOutput(writes ...io.Writer) *Logger {
return std.SetOutput(writes...)
}
func GetOutputWriter(filename string) io.Writer {
if filepath.Dir(filename) != filename && !isDir(filepath.Dir(filename)) {
err := os.MkdirAll(filepath.Dir(filename), os.ModePerm)
if err != nil {
Errorf("err:%v", err)
}
}
hook, err := rotatelogs.New(filename)
if err != nil {
std.Panicf("err:%v", err)
}
return hook
}
func isDir(path string) bool {
s, err := os.Stat(path)
if err != nil {
return false
}
return s.IsDir()
}
var (
cleanRotatelogOnce = make(map[string]bool)
)
func GetOutputWriterHourly(filename string) Writer {
if filepath.Dir(filename) != filename && !isDir(filepath.Dir(filename)) {
err := os.MkdirAll(filepath.Dir(filename), os.ModePerm)
if err != nil {
Errorf("err:%v", err)
}
}
hook, err := rotatelogs.
New(filename+"%Y%m%d%H.log",
rotatelogs.WithLinkName(filename+".log"),
rotatelogs.WithRotationSize(1024*1024*8*100),
rotatelogs.WithRotationTime(time.Hour),
rotatelogs.WithRotationCount(12),
)
if err != nil {
std.Panicf("err:%v", err)
}
if _, ok := cleanRotatelogOnce[filename]; !ok {
go func() {
for {
files, err := os.ReadDir(filepath.Dir(filename))
if err != nil {
fmt.Printf("err:%v\n", err)
continue
}
pie.Each(
pie.DropTop(
pie.SortUsing(
pie.Map(
files,
func(file os.DirEntry) string {
return file.Name()
},
),
func(a, b string) bool {
return a > b
},
),
12,
),
func(s string) {
if s == ".log" {
return
}
fmt.Printf("remove:%s\n", s)
err = os.Remove(filepath.Join(filepath.Dir(filename), s))
if err != nil {
Errorf("err:%v", err)
}
})
time.Sleep(time.Minute * 10)
}
}()
cleanRotatelogOnce[filename] = true
}
return hook
}