-
Notifications
You must be signed in to change notification settings - Fork 13
/
log.go
132 lines (112 loc) · 2.47 KB
/
log.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
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
package pairec
import (
"flag"
"fmt"
"io/ioutil"
"os"
"path/filepath"
"sort"
"time"
"github.com/alibaba/pairec/v2/datasource/sls"
"github.com/alibaba/pairec/v2/log"
"github.com/alibaba/pairec/v2/recconf"
)
const (
LOG_DEBUG = "DEBUG"
LOG_INFO = "INFO"
LOG_ERROR = "ERROR"
LOG_FATAL = "FATAL"
LOG_OUTPUT_CONSOLE = "console"
)
var logDir string
func ClearDir(config recconf.LogConfig) {
if config.LogLevel == LOG_DEBUG {
flag.Set("v", "1")
}
if config.Output == LOG_OUTPUT_CONSOLE {
flag.Set("logtostderr", "true")
}
if f := flag.Lookup("log_dir"); f != nil {
logDir = f.Value.String()
}
if logDir != "" {
go clearLoop(config)
}
if config.SLSName != "" {
if slsclient, err := sls.GetSlsClient(config.SLSName); err == nil {
log.RegisterSlsClient(slsclient)
}
}
}
type fileInfo struct {
file os.FileInfo
delete bool
}
type fileInfoSlice []*fileInfo
func (us fileInfoSlice) Len() int {
return len(us)
}
func (us fileInfoSlice) Less(i, j int) bool {
return us[i].file.ModTime().Unix() < us[j].file.ModTime().Unix()
}
func (us fileInfoSlice) Swap(i, j int) {
tmp := us[i]
us[i] = us[j]
us[j] = tmp
}
func clearLoop(config recconf.LogConfig) {
fileInfoList := make([]*fileInfo, 0)
fmt.Println("setup clean log dir", logDir)
for {
fileInfoList = fileInfoList[:0]
fileInfos, err := ioutil.ReadDir(logDir)
if err != nil {
fmt.Println(err)
continue
}
pointTime := time.Now().Unix() - int64(config.RetensionDays*86400)
totalSize := int64(0)
for _, file := range fileInfos {
if file.ModTime().Unix() < pointTime {
path := filepath.Join(logDir, file.Name())
err := os.Remove(path)
if err != nil {
fmt.Println(err)
}
continue
}
// omit symlink file
if file.Mode() == os.ModeSymlink {
continue
}
totalSize += file.Size()
info := &fileInfo{
delete: false,
file: file,
}
fileInfoList = append(fileInfoList, info)
}
sizeThreshold := int64(float64(config.DiskSize*1024*1024*1024) * 0.8)
// sizeThreshold := int64(0)
if totalSize > sizeThreshold {
sort.Sort(fileInfoSlice(fileInfoList))
for _, info := range fileInfoList {
info.delete = true
totalSize -= info.file.Size()
if totalSize < sizeThreshold {
break
}
}
for _, info := range fileInfoList {
if info.delete {
path := filepath.Join(logDir, info.file.Name())
err := os.Remove(path)
if err != nil {
fmt.Println(err)
}
}
}
}
time.Sleep(10 * time.Second)
}
}