-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathappender_file.go
81 lines (66 loc) · 1.72 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
package golog
import (
"os"
"sync"
)
// defaultBufferSize
const defaultBufferSize = 4096
// FileAppender
type FileAppender struct {
file *os.File
bufferedWriter *bufferedWriter
mu *sync.Mutex
activated bool
}
// NewFileAppender returns new FileAppender
func NewFileAppender(fileName string) (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
}
return &FileAppender{
file: file,
bufferedWriter: newBufferedWriter(file, withBufferSize(defaultBufferSize)),
mu: new(sync.Mutex),
activated: true,
}, nil
}
// NewFileAppender returns new FileAppender
func NewFileAppenderWithBufferSize(fileName string, bufferSize int) (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
}
return &FileAppender{
file: file,
bufferedWriter: newBufferedWriter(file, withBufferSize(size)),
mu: new(sync.Mutex),
activated: true,
}, nil
}
// Write implements io.Write
func (appender *FileAppender) Write(data []byte) (n int, err error) {
appender.mu.Lock()
defer appender.mu.Unlock()
data = append(data, '\n')
return appender.bufferedWriter.Write(data)
}
// Close implements io.Closer
func (appender *FileAppender) Close() error {
appender.mu.Lock()
defer func() {
appender.mu.Unlock()
appender.activated = false
}()
if appender.activated {
if err := appender.bufferedWriter.Flush(); err != nil {
return err
}
return appender.file.Close()
}
return nil
}