forked from morita-kuma/golog
-
Notifications
You must be signed in to change notification settings - Fork 0
/
appender_file_rotatable.go
75 lines (60 loc) · 1.98 KB
/
appender_file_rotatable.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
package golog
import (
"os"
"os/signal"
"sync"
"syscall"
"time"
)
// RotatableFileAppender RotatableFileAppender struct
type RotatableFileAppender struct {
*FileAppender
mu *sync.Mutex
}
// NewRotatableFileAppender returns new FileAppender
func NewRotatableFileAppender(fileName string) (asyncFileAppender *RotatableFileAppender, err error) {
return NewRotatableFileAppenderWithBufferSize(fileName, defaultBufferSize)
}
// NewRotatableFileAppenderWithBufferSize returns new FileAppender
func NewRotatableFileAppenderWithBufferSize(fileName string, bufferSize int) (asyncFileAppender *RotatableFileAppender, err error) {
return NewRotatableFileAppenderWithBufferSizeAndFlushInterval(fileName, bufferSize, defaultFlushInterval)
}
// NewRotatableFileAppenderWithBufferSizeAndFlushInterval returns new FileAppender
func NewRotatableFileAppenderWithBufferSizeAndFlushInterval(fileName string, bufferSize int, flushInterval time.Duration) (asyncFileAppender *RotatableFileAppender, err error) {
fileAppender, err := NewFileAppenderWithBufferSizeAndFlushInterval(fileName, bufferSize, flushInterval)
if err != nil {
return nil, err
}
appender := &RotatableFileAppender{
FileAppender: fileAppender,
mu: new(sync.Mutex),
}
hup := make(chan os.Signal, 1)
signal.Notify(hup, syscall.SIGHUP)
go func() {
for {
<-hup
appender.mu.Lock()
appender.FileAppender.Close()
newAppender, err := NewFileAppenderWithBufferSizeAndFlushInterval(fileName, bufferSize, flushInterval)
if err != nil {
panic(err)
}
appender.FileAppender = newAppender
appender.mu.Unlock()
}
}()
return appender, nil
}
// Write implements io.Write
func (appender *RotatableFileAppender) Write(data []byte) (n int, err error) {
appender.mu.Lock()
defer appender.mu.Unlock()
return appender.FileAppender.Write(data)
}
// Close implements io.Closer
func (appender *RotatableFileAppender) Close() error {
appender.mu.Lock()
defer appender.mu.Unlock()
return appender.FileAppender.Close()
}