forked from morita-kuma/golog
-
Notifications
You must be signed in to change notification settings - Fork 0
/
appender_file.go
103 lines (87 loc) · 2.24 KB
/
appender_file.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
package golog
import (
"context"
"fmt"
"os"
"sync"
"time"
)
// defaultBufferSize
const defaultBufferSize = 4096
const defaultFlushInterval = time.Minute * 5
// FileAppender
type FileAppender struct {
file *os.File
bufferedWriter *bufferedWriter
mu *sync.Mutex
activated bool
ticker *time.Ticker
stopTicker context.CancelFunc
}
// NewFileAppender returns new FileAppender
func NewFileAppender(fileName string) (asyncFileAppender *FileAppender, err error) {
return NewFileAppenderWithBufferSizeAndFlushInterval(fileName, defaultBufferSize, defaultFlushInterval)
}
// NewFileAppenderWithBufferSizeAndFlushInterval returns new FileAppender
func NewFileAppenderWithBufferSizeAndFlushInterval(fileName string, bufferSize int, flushInterval time.Duration) (asyncFileAppender *FileAppender, err error) {
file, err := os.OpenFile(fileName, os.O_WRONLY|os.O_CREATE|os.O_APPEND, 0666)
if err != nil {
return nil, err
}
size := defaultBufferSize
if bufferSize > 0 {
size = bufferSize
}
ctx, cancel := context.WithCancel(context.Background())
appender := &FileAppender{
file: file,
bufferedWriter: newBufferedWriter(file, withBufferSize(size)),
mu: new(sync.Mutex),
activated: true,
ticker: time.NewTicker(flushInterval),
stopTicker: cancel,
}
go func() {
for {
select {
case <-appender.ticker.C:
case <-ctx.Done():
}
appender.mu.Lock()
if !appender.activated {
appender.ticker.Stop()
appender.mu.Unlock()
return
}
appender.bufferedWriter.Flush()
appender.mu.Unlock()
}
}()
return appender, nil
}
// Write implements io.Write
func (appender *FileAppender) Write(data []byte) (n int, err error) {
appender.mu.Lock()
defer appender.mu.Unlock()
if appender.activated {
data = append(data, '\n')
return appender.bufferedWriter.Write(data)
}
return 0, fmt.Errorf("appender is closed")
}
// Close implements io.Closer
func (appender *FileAppender) Close() error {
appender.mu.Lock()
defer func() {
appender.activated = false
appender.stopTicker()
appender.mu.Unlock()
}()
if appender.activated {
if err := appender.bufferedWriter.Flush(); err != nil {
return err
}
return appender.file.Close()
}
return nil
}