-
Notifications
You must be signed in to change notification settings - Fork 13
/
file_writer.go
185 lines (158 loc) · 4.81 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
package rotate
// Rotating things
import (
"fmt"
"io"
"os"
"path/filepath"
"sort"
"strconv"
"strings"
"sync"
"time"
)
// FilePerm defines the permissions that Writer will use for all
// the files it creates.
const (
FilePerm = os.FileMode(0644)
DateFormat = "2006-01-02"
)
// FileWriter implements the io.Writer interface and writes to the
// filename specified.
// Will rotate at the specified interval and/or when the current file size exceeds maxSizeInBytes
// At rotation time, current file is renamed and a new file is created.
// If the number of archives exceeds maxArchives, older files are deleted.
type FileWriter struct {
filename string
filenameRotationTemplate string
current *os.File
interval time.Duration
maxSizeInBytes int64
maxArchives int
expireTime time.Time
bytesWritten int64
sync.Mutex
}
// NewFileWriter creates a new file writer.
func NewFileWriter(filename string, interval time.Duration, maxSizeInBytes int64, maxArchives int) (io.WriteCloser, error) {
if interval == 0 && maxSizeInBytes <= 0 {
// No rotation needed so a basic io.Writer will do the trick
return openFile(filename)
}
w := &FileWriter{
filename: filename,
interval: interval,
maxSizeInBytes: maxSizeInBytes,
maxArchives: maxArchives,
filenameRotationTemplate: getFilenameRotationTemplate(filename),
}
if err := w.openCurrent(); err != nil {
return nil, err
}
return w, nil
}
func openFile(filename string) (*os.File, error) {
return os.OpenFile(filename, os.O_RDWR|os.O_CREATE|os.O_APPEND, FilePerm)
}
func getFilenameRotationTemplate(filename string) string {
// Extract the file extension
fileExt := filepath.Ext(filename)
// Remove the file extension from the filename (if any)
stem := strings.TrimSuffix(filename, fileExt)
return stem + ".%s-%s" + fileExt
}
// Write writes p to the current file, then checks to see if
// rotation is necessary.
func (w *FileWriter) Write(p []byte) (n int, err error) {
w.Lock()
defer w.Unlock()
if n, err = w.current.Write(p); err != nil {
return 0, fmt.Errorf("write: %w", err)
}
w.bytesWritten += int64(n)
if err = w.rotateIfNeeded(); err != nil {
return 0, err
}
return n, nil
}
// Close closes the current file. Writer is unusable after this
// is called.
func (w *FileWriter) Close() (err error) {
w.Lock()
defer w.Unlock()
// Rotate before closing
if err = w.rotate(); err != nil {
return err
}
w.current = nil
return nil
}
func (w *FileWriter) openCurrent() (err error) {
// In case ModTime() fails, we use time.Now()
w.expireTime = time.Now().Add(w.interval)
w.bytesWritten = 0
w.current, err = openFile(w.filename)
if err != nil {
return err
}
// Goal here is to rotate old pre-existing files.
// For that we use fileInfo.ModTime, instead of time.Now().
// Example: agent is restarted every 23 hours and
// the rotation interval is set to 24 hours.
// With time.now() as a reference we'd never rotate the file.
if fileInfo, err := w.current.Stat(); err == nil {
w.expireTime = fileInfo.ModTime().Add(w.interval)
w.bytesWritten = fileInfo.Size()
}
if err = w.rotateIfNeeded(); err != nil {
return err
}
return nil
}
func (w *FileWriter) rotateIfNeeded() error {
if (w.interval > 0 && time.Now().After(w.expireTime)) ||
(w.maxSizeInBytes > 0 && w.bytesWritten >= w.maxSizeInBytes) {
if err := w.rotate(); err != nil {
// Ignore rotation errors and keep the log open
fmt.Printf("unable to rotate the file '%s', %s", w.filename, err.Error())
}
return w.openCurrent()
}
return nil
}
func (w *FileWriter) rotate() (err error) {
if err = w.current.Close(); err != nil {
return fmt.Errorf("close: %w", err)
}
// Use year-month-date for readability, unix time to make the file name unique with second precision
now := time.Now()
rotatedFilename := fmt.Sprintf(w.filenameRotationTemplate, now.Format(DateFormat), strconv.FormatInt(now.Unix(), 10))
if err = os.Rename(w.filename, rotatedFilename); err != nil {
return fmt.Errorf("rename: %w", err)
}
if err = w.purgeArchivesIfNeeded(); err != nil {
return err
}
return nil
}
func (w *FileWriter) purgeArchivesIfNeeded() (err error) {
if w.maxArchives == -1 {
// Skip archiving
return nil
}
var matches []string
if matches, err = filepath.Glob(fmt.Sprintf(w.filenameRotationTemplate, "*", "*")); err != nil {
return fmt.Errorf("glob: %w", err)
}
// if there are more archives than the configured maximum, then purge older files
if len(matches) > w.maxArchives {
// sort files alphanumerically to delete older files first
sort.Strings(matches)
for _, filename := range matches[:len(matches)-w.maxArchives] {
if err = os.Remove(filename); err != nil {
return fmt.Errorf("remove: %w", err)
}
}
}
return nil
}