-
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathfile_handler.go
More file actions
304 lines (250 loc) · 6.27 KB
/
file_handler.go
File metadata and controls
304 lines (250 loc) · 6.27 KB
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
package log
import (
"bytes"
"compress/gzip"
"context"
"errors"
"fmt"
"io"
"os"
"path/filepath"
"strings"
"sync"
"sync/atomic"
"time"
)
var fileHandlers = sync.Map{} // map[string]*refCountedFileHandler
type refCountedFileHandler struct {
handler *FileHandler
count int32
}
// NewFileHandler creates a new FileHandler and starts it.
func NewFileHandler(path string) (*FileHandler, error) {
return newRefCounted(newFileHandler(path))
}
func newRefCounted(fh *FileHandler) (*FileHandler, error) {
newPth := filepath.Join(fh.logDir, fh.logFilename)
val, _ := fileHandlers.LoadOrStore(newPth, &refCountedFileHandler{
handler: fh,
})
var once sync.Once
rh := val.(*refCountedFileHandler)
rh.handler.release = func() bool {
if atomic.AddInt32(&rh.count, -1) == 0 {
once.Do(func() {
rh.handler.muFile.Lock()
defer rh.handler.muFile.Unlock()
rh.handler.running = false
})
return true
}
return false
}
var once2 sync.Once
rh.handler.onRelease = func() {
once2.Do(func() {
rh.handler.muFile.Lock()
defer rh.handler.muFile.Unlock()
ptr := rh.handler.filePtr
if ptr != nil {
_ = ptr.Sync()
_ = ptr.Close()
rh.handler.filePtr = nil
}
fileHandlers.Delete(newPth)
})
}
if atomic.AddInt32(&rh.count, 1) == 1 {
if err := rh.handler.Start(); err != nil && !errors.Is(err, ErrAlreadyStarted) {
fileHandlers.Delete(newPth)
return nil, err
}
}
return rh.handler, nil
}
type FileHandler struct {
BaseHandler
muFile sync.Mutex // covers filePtr and logCh
logDir string
logFilename string
filePtr *os.File
maxFileSize int64 // exceeding this size will trigger log rotation. defaults to 10MB. set to 0 to disable
release func() bool // returns true if the handler is no longer in use
onRelease func()
}
func newFileHandler(path string) *FileHandler {
f := &FileHandler{
logDir: filepath.Dir(path),
logFilename: filepath.Base(path),
}
f.BaseHandler = BaseHandler{
CancelPreFunc: func(ctx context.Context, lh LogHandler) error {
if f.release != nil {
if !f.release() {
return ErrSkipClose
}
f.release = nil
}
return nil
},
CloseFunc: func(ctx context.Context, lh LogHandler) error {
if f.onRelease != nil {
f.onRelease()
}
return nil
},
StartFunc: func(ctx context.Context, lh LogHandler) error {
_, base := f.getLogfileLocation()
if base == "." {
return ErrMissingLogFilename
}
logfile, err := f.ensureLogFile()
if err != nil {
return fmt.Errorf("failed to open log file: %w", err)
}
f.filePtr = logfile
return nil
},
HandleFunc: func(ctx context.Context, msg *LogMessage) error {
f.muFile.Lock()
defer f.muFile.Unlock()
if f.filePtr == nil {
panic("FileHandler: filePtr is nil")
}
_, err := f.filePtr.WriteString(msg.String(""))
if err != nil {
return err
}
return nil
},
Subprocesses: []func(context.Context) error{f.logRotater},
}
return f
}
func (f *FileHandler) logRotater(ctx context.Context) error {
ticker := time.NewTicker(time.Minute)
defer ticker.Stop()
for {
select {
case <-ctx.Done():
return nil
case <-ticker.C:
maxFilesize := f.GetMaxFileSize()
if maxFilesize == 0 {
return nil
}
logDir, logFilename := f.GetLogfileLocation()
logPath := filepath.Join(logDir, logFilename)
rotatedName := fmt.Sprintf("%s-%s.gz", logFilename, time.Now().UTC().Format("2006-01-02_15-04-05"))
rotatedPath := filepath.Join(logDir, rotatedName)
info, err := os.Stat(logPath)
if err != nil {
if os.IsNotExist(err) {
f.muFile.Lock()
_, err := f.ensureLogFile()
f.muFile.Unlock()
if err != nil {
return fmt.Errorf("failed to recreate missing log file, killing rotation: %w", err)
}
continue
}
f.wg.Done()
return fmt.Errorf("failed to stat log file, killing rotation: %w", err)
}
if info.Size() <= maxFilesize {
continue
}
f.muFile.Lock()
original, err := os.Open(filepath.Clean(logPath))
if err != nil {
f.muFile.Unlock()
Error().Msgf("failed to open log for rotation: %v", err).Send()
continue
}
var buf bytes.Buffer
gz := gzip.NewWriter(&buf)
_, err = io.Copy(gz, original)
_ = original.Close()
_ = gz.Close()
if err != nil {
f.muFile.Unlock()
Error().Msgf("failed to compress rotated log: %v", err).Send()
continue
}
if err := os.WriteFile(rotatedPath, buf.Bytes(), 0o600); err != nil {
f.muFile.Unlock()
Error().Msgf("failed to write rotated log file: %v", err).Send()
continue
}
if err := os.Truncate(logPath, 0); err != nil {
Error().Msgf("failed to truncate original log after rotation: %v", err).Send()
}
f.muFile.Unlock()
}
}
}
func (f *FileHandler) getLogfileLocation() (dir, base string) {
return f.logDir, f.logFilename
}
func (f *FileHandler) GetLogfileLocation() (dir, base string) {
f.mu.RLock()
defer f.mu.RUnlock()
return f.getLogfileLocation()
}
func (f *FileHandler) SetMaxFileSize(size int64) {
f.mu.Lock()
f.maxFileSize = size
f.mu.Unlock()
}
func (f *FileHandler) GetMaxFileSize() int64 {
f.mu.RLock()
defer f.mu.RUnlock()
return f.maxFileSize
}
func (f *FileHandler) SetLogfileLocation(dir, base string) error {
f.mu.Lock()
defer f.mu.Unlock()
path := filepath.Join(dir, base)
if path == "." {
return ErrMissingLogFilename
}
path = strings.TrimSuffix(path, ".log") + ".log"
f.logDir, f.logFilename = filepath.Split(path)
return nil
}
func (f *FileHandler) ensureLogDir() error {
if f.logDir == "." {
return nil
}
return os.MkdirAll(filepath.Clean(f.logDir), 0o700)
}
func (f *FileHandler) ensureLogFile() (*os.File, error) {
if f.logFilename == "." {
return nil, ErrNoLogFileConfigured
}
if err := f.ensureLogDir(); err != nil {
return nil, err
}
logfileLocation := filepath.Join(f.logDir, f.logFilename)
if logfileLocation == "." {
return nil, ErrNoLogFileConfigured
}
stat, err := os.Stat(logfileLocation)
if err != nil && !os.IsNotExist(err) {
return nil, err
}
if os.IsNotExist(err) {
return f.openLogFile()
}
if stat.IsDir() {
return nil, ErrFoundDirWhenExpectingFile
}
return f.openLogFile()
}
func (f *FileHandler) openLogFile() (*os.File, error) {
return os.OpenFile(
filepath.Join(f.logDir, f.logFilename),
os.O_APPEND|os.O_CREATE|os.O_WRONLY,
0o600,
)
}