-
Notifications
You must be signed in to change notification settings - Fork 0
/
rotate.go
246 lines (161 loc) · 3.75 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
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
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
package gorotatelogs
import (
"errors"
"math"
"os"
"path/filepath"
"strconv"
"strings"
"sync"
"time"
)
type Config struct {
// if true it will remove file with mod time before MaxAge
CleanOldFiles bool
// if true it will add "-" + FormatTime
UsingTime bool
// required in Megabyte MB. etc: 10 is equal to 10MB
MaxSize int
// required CleanOldFiles true. if not provide it will default using 7. etc: equal to 7 days before now
MaxAge int
// required
Directory string
// required. name file end .log extension
Filename string
// if not provide it will default use "backup"
BackupName string
// required UsingTime True. if no format it will default using rfc3399
FormatTime string
}
type RotateLogsWriter struct {
mut sync.Mutex
Config Config
file *os.File
}
// write func to satisfy io.writer interface
func (w *RotateLogsWriter) Write(p []byte) (n int, err error) {
w.mut.Lock()
defer w.mut.Unlock()
if w.file != nil {
err = w.file.Close()
w.file = nil
if err != nil {
return
}
}
err = w.rotate(p)
if err != nil {
return
}
return w.file.Write(p)
}
func (w *RotateLogsWriter) rotate(p []byte) (err error) {
tempFilename := w.Config.Filename
if w.Config.Directory == "" {
err = errors.New("no dir. plase provided")
return
}
if w.Config.MaxSize == 0 {
err = errors.New("no maxsize. plase provided")
return
}
err = os.MkdirAll(w.Config.Directory, os.ModePerm)
if err != nil {
return
}
if w.Config.CleanOldFiles {
if w.Config.MaxAge == 0 {
w.Config.MaxAge = 7
}
go func() {
err = w.clean()
}()
}
str := strings.Split(w.Config.Filename, ".log")
if w.Config.UsingTime && !strings.Contains(w.Config.Filename, time.Now().Format(w.Config.FormatTime)) {
if w.Config.FormatTime == "" {
w.Config.FormatTime = time.RFC3339
}
w.Config.Filename = str[0] + "-" + time.Now().Format(w.Config.FormatTime) + ".log"
}
if w.Config.BackupName == "" {
w.Config.BackupName = "backup"
}
pathFile := filepath.Join(w.Config.Directory, w.Config.Filename)
info, err := os.Stat(pathFile)
if err == nil {
// if file size over maxsize rename to backup and create new file
if ((info.Size() + int64(len(p))) / 1000000) > int64(w.Config.MaxSize) {
err = w.backup(pathFile, tempFilename)
if err != nil {
return
}
return
}
} else if os.IsNotExist(err) {
w.file, err = os.Create(pathFile)
if err != nil {
return
}
// reset filename
w.Config.Filename = tempFilename
return
}
w.file, err = os.OpenFile(pathFile, os.O_APPEND|os.O_WRONLY, os.ModePerm)
if err != nil {
return
}
// reset filename
w.Config.Filename = tempFilename
return
}
func (w *RotateLogsWriter) backup(pathFile, tempFilename string) (err error) {
var count int
newStr := strings.Split(w.Config.Filename, ".log")
dir, err := os.ReadDir(w.Config.Directory)
if err != nil {
return
}
count = len(dir)
if w.Config.UsingTime {
count = 0
for _, v := range dir {
if strings.Contains(v.Name(), time.Now().Format(w.Config.FormatTime)) {
count++
}
}
}
i := strconv.Itoa(count)
err = os.Rename(pathFile, filepath.Join(w.Config.Directory, newStr[0]+"-"+w.Config.BackupName+"-"+i+".log"))
if err != nil {
return
}
w.file, err = os.Create(pathFile)
if err != nil {
return
}
// reset filename
w.Config.Filename = tempFilename
return
}
func (w *RotateLogsWriter) clean() (err error) {
ageTime := time.Now().AddDate(0, 0, -int(math.Abs(float64(w.Config.MaxAge))))
dir, err := os.ReadDir(w.Config.Directory)
if err != nil {
return
}
for _, v := range dir {
info, errInfo := v.Info()
if errInfo != nil {
err = errInfo
return
}
if ageTime.After(info.ModTime()) {
err = os.Remove(v.Name())
if err != nil {
return
}
}
}
return
}