-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathfile_writer.go
350 lines (306 loc) · 7.46 KB
/
file_writer.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
338
339
340
341
342
343
344
345
346
347
348
349
350
package log4go
import (
"bufio"
"bytes"
"errors"
"fmt"
"log"
"os"
"path"
"path/filepath"
"strconv"
"strings"
"sync"
"time"
)
var pathVariableTable map[byte]func(*time.Time) int
// FileWriter file writer for log record deal
type FileWriter struct {
// write log order by order and atomic incr
// maxLinesCurLines and maxSizeCurSize
level int
lock sync.RWMutex
initFileOnce sync.Once // init once
rotatePerm os.FileMode // real used
perm string // input
// input filename
filename string
// The opened file
file *os.File
fileBufWriter *bufio.Writer
// like "xwi88.log", xwi88 is filenameOnly and .log is suffix
filenameOnly, suffix string
pathFmt string // Rotate when, use actions
actions []func(*time.Time) int
variables []interface{}
// // Rotate at file lines
// maxLines int // Rotate at line
// maxLinesCurLines int
// // Rotate at size
// maxSize int
// maxSizeCurSize int
lastWriteTime time.Time
initFileOk bool
rotate bool
// Rotate daily
daily bool
// Rotate hourly
hourly bool
// Rotate minutely
minutely bool
maxDays int
dailyOpenDate int
dailyOpenTime time.Time
// Rotate hourly
maxHours int
hourlyOpenDate int
hourlyOpenTime time.Time
// Rotate minutely
maxMinutes int
minutelyOpenDate int
minutelyOpenTime time.Time
}
// FileWriterOptions file writer options
type FileWriterOptions struct {
Level string `json:"level" mapstructure:"level"`
Filename string `json:"filename" mapstructure:"filename"`
Enable bool `json:"enable" mapstructure:"enable"`
Rotate bool `json:"rotate" mapstructure:"rotate"`
// Rotate daily
Daily bool `json:"daily" mapstructure:"daily"`
// Rotate hourly
Hourly bool `json:"hourly" mapstructure:"hourly"`
// Rotate minutely
Minutely bool `json:"minutely" mapstructure:"minutely"`
MaxDays int `json:"max_days" mapstructure:"max_days"`
MaxHours int `json:"max_hours" mapstructure:"max_hours"`
MaxMinutes int `json:"max_minutes" mapstructure:"max_minutes"`
}
// NewFileWriter create new file writer
func NewFileWriter() *FileWriter {
return &FileWriter{}
}
// NewFileWriterWithOptions create new file writer with options
func NewFileWriterWithOptions(options FileWriterOptions) *FileWriter {
defaultLevel := DEBUG
if len(options.Level) > 0 {
defaultLevel = getLevelDefault(options.Level, defaultLevel, "")
}
fileWriter := &FileWriter{
level: defaultLevel,
filename: options.Filename,
rotate: options.Rotate,
daily: options.Daily,
maxDays: options.MaxDays,
hourly: options.Hourly,
maxHours: options.MaxHours,
minutely: options.Minutely,
maxMinutes: options.MaxMinutes,
}
if err := fileWriter.SetPathPattern(options.Filename); err != nil {
log.Printf("[log4go] file writer init err: %v", err.Error())
}
return fileWriter
}
// Write file write
func (w *FileWriter) Write(r *Record) error {
if r.level > w.level {
return nil
}
if w.fileBufWriter == nil {
return errors.New("fileWriter no opened file: " + w.filename)
}
_, err := w.fileBufWriter.WriteString(r.String())
return err
}
// Init file writer init
func (w *FileWriter) Init() error {
filename := w.filename
defaultPerm := "0755"
if len(filename) != 0 {
w.suffix = filepath.Ext(filename)
w.filenameOnly = strings.TrimSuffix(filename, w.suffix)
w.filename = filename
if w.suffix == "" {
w.suffix = ".log"
}
}
if w.perm == "" {
w.perm = defaultPerm
}
perm, err := strconv.ParseInt(w.perm, 8, 64)
if err != nil {
return err
}
w.rotatePerm = os.FileMode(perm)
if w.rotate {
if w.daily && w.maxDays <= 0 {
w.maxDays = 60
}
if w.hourly && w.maxHours <= 0 {
w.maxHours = 12
}
if w.minutely && w.maxMinutes <= 0 {
w.maxMinutes = 1
}
}
return w.Rotate()
}
// Flush writes any buffered data to file
func (w *FileWriter) Flush() error {
if w.fileBufWriter != nil {
return w.fileBufWriter.Flush()
}
return nil
}
// SetPathPattern for file writer
func (w *FileWriter) SetPathPattern(pattern string) error {
n := 0
for _, c := range pattern {
if c == '%' {
n++
}
}
if n == 0 {
w.pathFmt = pattern
return nil
}
w.actions = make([]func(*time.Time) int, 0, n)
w.variables = make([]interface{}, n, n)
tmp := []byte(pattern)
variable := 0
for _, c := range tmp {
if variable == 1 {
act, ok := pathVariableTable[c]
if !ok {
return errors.New("invalid rotate pattern (" + pattern + ")")
}
w.actions = append(w.actions, act)
variable = 0
continue
}
if c == '%' {
variable = 1
}
}
w.pathFmt = convertPatternToFmt(tmp)
return nil
}
func (w *FileWriter) initFile() {
w.lock.Lock()
defer w.lock.Unlock()
w.initFileOk = true
}
// Rotate file writer rotate
func (w *FileWriter) Rotate() error {
now := time.Now()
v := 0
rotate := false
for i, act := range w.actions {
v = act(&now)
if v != w.variables[i] {
if !w.initFileOk {
w.variables[i] = v
rotate = true
} else {
// only exec except the first round
switch i {
case 2:
if w.daily {
w.dailyOpenDate = v
w.dailyOpenTime = now
_, _, d := w.lastWriteTime.AddDate(0, 0, w.maxDays).Date()
if v == d {
rotate = true
w.variables[i] = v
}
}
case 3:
if w.hourly {
w.hourlyOpenDate = v
w.hourlyOpenTime = now
h := w.lastWriteTime.Add(time.Hour * time.Duration(w.maxHours)).Hour()
if v == h {
rotate = true
w.variables[i] = v
}
}
case 4:
if w.minutely {
w.minutelyOpenDate = v
w.minutelyOpenTime = now
m := w.lastWriteTime.Add(time.Minute * time.Duration(w.maxMinutes)).Minute()
if v == m {
rotate = true
w.variables[i] = v
}
}
}
}
}
}
// must init file first!
if rotate == false {
return nil
}
w.initFileOnce.Do(w.initFile)
w.lastWriteTime = now
if w.fileBufWriter != nil {
if err := w.fileBufWriter.Flush(); err != nil {
return err
}
}
if w.file != nil {
if err := w.file.Close(); err != nil {
return err
}
}
filePath := fmt.Sprintf(w.pathFmt, w.variables...)
if err := os.MkdirAll(path.Dir(filePath), w.rotatePerm); err != nil {
if !os.IsExist(err) {
return err
}
}
if file, err := os.OpenFile(filePath, os.O_RDWR|os.O_CREATE|os.O_APPEND, w.rotatePerm); err == nil {
w.file = file
} else {
return err
}
if w.fileBufWriter = bufio.NewWriterSize(w.file, 8192); w.fileBufWriter == nil {
return errors.New("fileWriter new fileBufWriter failed")
}
w.suffix = filepath.Ext(filePath)
w.filenameOnly = strings.TrimSuffix(filePath, w.suffix)
return nil
}
func getYear(now *time.Time) int {
return now.Year()
}
func getMonth(now *time.Time) int {
return int(now.Month())
}
func getDay(now *time.Time) int {
return now.Day()
}
func getHour(now *time.Time) int {
return now.Hour()
}
func getMin(now *time.Time) int {
return now.Minute()
}
func convertPatternToFmt(pattern []byte) string {
pattern = bytes.Replace(pattern, []byte("%Y"), []byte("%d"), -1)
pattern = bytes.Replace(pattern, []byte("%M"), []byte("%02d"), -1)
pattern = bytes.Replace(pattern, []byte("%D"), []byte("%02d"), -1)
pattern = bytes.Replace(pattern, []byte("%H"), []byte("%02d"), -1)
pattern = bytes.Replace(pattern, []byte("%m"), []byte("%02d"), -1)
return string(pattern)
}
func init() {
pathVariableTable = make(map[byte]func(*time.Time) int, 5)
pathVariableTable['Y'] = getYear
pathVariableTable['M'] = getMonth
pathVariableTable['D'] = getDay
pathVariableTable['H'] = getHour
pathVariableTable['m'] = getMin
}