-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathrotatelogs.go
337 lines (272 loc) · 7.01 KB
/
rotatelogs.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
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
package rotatelogs
import (
"errors"
"fmt"
"os"
"path/filepath"
"sort"
"strings"
"sync"
"time"
)
type rotateConfig struct {
fileBasePath string
fileDateTimeLayout string
maxAge time.Duration
maxNum int
logChannelLen int
rotationTime time.Duration
rotateLogFileMaxSize int64
fileExt string
}
type logFile struct {
filePath string
dateTime time.Time
}
type hisLogFile struct {
files []logFile
}
type RotateLogs struct {
rotateConfig
hisLogFile
currFileName string
currFileDate time.Time
currFileSize int64
eventChannel chan bool
writer IWriter
outFh *os.File
outMutex sync.Mutex
nextRotateTime time.Time
}
func (rl *RotateLogs) Write(p []byte) (int, error) {
ok := rl.rotateFileTime()
n, err := rl.writer.Write(p)
if err != nil {
return 0, err
}
if !ok {
err = rl.rotateFileSize(len(p))
}
return n, err
}
func (rl *RotateLogs) getNextRotationTime() time.Time {
nowTime := time.Now()
zeroDate := time.Date(nowTime.Year(), nowTime.Month(), nowTime.Day(), 0, 0, 0, 0, time.Local)
passTime := nowTime.Sub(zeroDate)
passCnt := passTime/rl.rotationTime + 1
return zeroDate.Add(passCnt * rl.rotationTime)
}
func (rl *RotateLogs) rotateFileTime() bool {
if rl.rotationTime == 0 {
return false
}
if time.Now().Before(rl.nextRotateTime) {
return false
}
rl.nextRotateTime = rl.getNextRotationTime()
return rl.rotateFile() == nil
}
func (rl *RotateLogs) rotateFileSize(size int) error {
if rl.rotateLogFileMaxSize <= 0 {
return nil
}
rl.currFileSize += int64(size)
if rl.currFileSize < rl.rotateLogFileMaxSize {
return nil
}
return rl.rotateFile()
}
func (rl *RotateLogs) setNewFD(fd *os.File, fileName string, fileSize int64) {
if rl.outFh != nil {
rl.outFh.Close()
rl.appendNewFile(rl.currFileName)
}
rl.outFh = fd
rl.currFileName = fileName
rl.currFileSize = fileSize
}
func (rl *RotateLogs) rotateFile() error {
fh, fileName, fileSize, err := rl.openNewFile()
if err != nil {
return err
}
rl.outMutex.Lock()
defer rl.outMutex.Unlock()
rl.setNewFD(fh, fileName, fileSize)
return nil
}
func (rl *RotateLogs) writeToFile(p []byte) (int, error) {
rl.outMutex.Lock()
defer rl.outMutex.Unlock()
return rl.outFh.Write(p)
}
func (rl *RotateLogs) Sync() error {
err := rl.writer.Sync()
if err != nil {
return err
}
rl.outMutex.Lock()
defer rl.outMutex.Unlock()
return rl.outFh.Sync()
}
// Close satisfies the io.Closer interface. You must
// call this method if you performed any writes to
// the object.
func (rl *RotateLogs) Close() error {
rl.writer.Close()
rl.outMutex.Lock()
defer rl.outMutex.Unlock()
return rl.outFh.Close()
}
func (rl *RotateLogs) setDefaultConfig() {
if rl.fileExt == "" {
rl.fileExt = DefaultFileExt
}
}
func (rl *RotateLogs) getFileName() string {
return filepath.Join(rl.fileBasePath, time.Now().Format(rl.fileDateTimeLayout)+rl.fileExt)
}
func (rl *RotateLogs) removeFile(files []string) {
go func() {
for _, file := range files {
os.Remove(file)
}
}()
}
func (rl *RotateLogs) appendNewFile(fileName string) {
if rl.maxNum == 0 && rl.maxAge == 0 {
return
}
var removeFile []string
rl.files = append(rl.files, logFile{filePath: fileName, dateTime: time.Now()})
if rl.maxNum > 0 && len(rl.files) > rl.maxNum {
removeNum := len(rl.files) - rl.maxNum
for i := 0; i < removeNum; i++ {
removeFile = append(removeFile, rl.files[i].filePath)
}
rl.files = rl.files[removeNum:]
}
if rl.maxAge > 0 {
removeIdx := -1
for i := range rl.files {
if rl.files[i].dateTime.Add(rl.maxAge).Before(time.Now()) {
removeFile = append(removeFile, rl.files[i].filePath)
removeIdx = i
} else {
break
}
}
rl.files = rl.files[removeIdx+1:]
}
rl.removeFile(removeFile)
}
func (rl *RotateLogs) walkLogs() {
if rl.maxNum == 0 && rl.maxAge == 0 {
return
}
// walk all file
filepath.Walk(rl.fileBasePath, func(path string, info os.FileInfo, err error) error {
if info.IsDir() {
return nil
}
if filepath.Ext(path) != rl.fileExt {
return nil
}
rl.files = append(rl.files, logFile{
filePath: path,
dateTime: info.ModTime(),
})
return nil
})
// sort files by mod time
sort.Slice(rl.files, func(i, j int) bool {
return rl.files[i].dateTime.Before(rl.files[j].dateTime)
})
}
func (rl *RotateLogs) prepare() error {
rl.walkLogs()
fh, fileName, size, err := rl.openNewFile()
if err != nil {
return err
}
rl.setNewFD(fh, fileName, size)
rl.currFileDate = time.Now()
if rl.rotationTime != 0 {
rl.nextRotateTime = rl.getNextRotationTime()
a := rl.nextRotateTime.Format("2006-01-02 15:04:05")
fmt.Println(a)
}
return nil
}
func (rl *RotateLogs) openNewFile() (*os.File, string, int64, error) {
// open the log file
filePathName := rl.getFileName()
dirName := filepath.Dir(filePathName)
if err := os.MkdirAll(dirName, 0755); err != nil {
return nil, "", 0, fmt.Errorf("failed to create directory %s", dirName)
}
fh, err := os.OpenFile(filePathName, os.O_CREATE|os.O_APPEND|os.O_WRONLY, 0644)
if err != nil {
return nil, "", 0, fmt.Errorf("failed to open file %ss", filePathName)
}
fInfo, err := fh.Stat()
if err != nil {
return nil, "", 0, fmt.Errorf("failed to stat file %ss", filePathName)
}
return fh, filePathName, fInfo.Size(), nil
}
func (rl *RotateLogs) isChangeDay() bool {
return time.Now().Year() != rl.currFileDate.Year() ||
time.Now().Month() != rl.currFileDate.Month() ||
time.Now().Day() != rl.currFileDate.Day()
}
func NewRotateLogs(basePath string, fileDateTimeLayout string, options ...Option) (*RotateLogs, error) {
dir, err := os.Stat(basePath)
if err != nil || dir.IsDir() == false {
return nil, errors.New("Not found dir " + basePath)
}
rl := &RotateLogs{}
rl.fileBasePath = basePath
err = checkFileNameDateTimeLayout(filepath.Base(fileDateTimeLayout))
if err != nil {
return nil, err
}
rl.fileExt = filepath.Ext(fileDateTimeLayout)
rl.fileDateTimeLayout = strings.TrimRight(fileDateTimeLayout, rl.fileExt)
for _, option := range options {
option.Configure(rl)
}
rl.setDefaultConfig()
err = rl.prepare()
if err != nil {
return nil, err
}
if rl.logChannelLen > 0 {
rl.writer = newChannelWriter(rl.writeToFile, rl.logChannelLen)
} else {
rl.writer = newFileWriter(rl.writeToFile)
}
return rl, nil
}
// WithFileNameDateTimeLayout 设置文件格式
func checkFileNameDateTimeLayout(fileNameDateTimeLayout string) error {
if strings.IndexAny(fileNameDateTimeLayout, "2006") == -1 {
return fmt.Errorf("invalid date time layout")
}
if strings.IndexAny(fileNameDateTimeLayout, "01") == -1 {
return fmt.Errorf("invalid date time layout")
}
if strings.IndexAny(fileNameDateTimeLayout, "02") == -1 {
return fmt.Errorf("invalid date time layout")
}
if strings.IndexAny(fileNameDateTimeLayout, "15") == -1 {
return fmt.Errorf("invalid date time layout")
}
if strings.IndexAny(fileNameDateTimeLayout, "04") == -1 {
return fmt.Errorf("invalid date time layout")
}
if strings.IndexAny(fileNameDateTimeLayout, "05") == -1 {
return fmt.Errorf("invalid date time layout")
}
return nil
}