-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathbuffer_syncer.go
86 lines (67 loc) · 1.45 KB
/
buffer_syncer.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
package xlogs
import (
"bufio"
"context"
"sync"
"time"
"go.uber.org/zap/zapcore"
)
type bufferWriterSyncer struct {
sync.Mutex
bufferWriter *bufio.Writer
ticker *time.Ticker
}
const (
defaultBufferSize = 256 * 1024
// 默认 1 秒刷盘一次
defaultFlushInterval = 1 * time.Second
)
type CloseFunc func() error
func Buffer(ws zapcore.WriteSyncer, bufferSize int, flushInterval time.Duration) (zapcore.WriteSyncer, CloseFunc) {
if _, ok := ws.(*bufferWriterSyncer); ok {
return ws, func() error { return nil }
}
ctx, cancel := context.WithCancel(context.Background())
if bufferSize == 0 {
bufferSize = defaultBufferSize
}
if flushInterval == 0 {
flushInterval = defaultFlushInterval
}
ticker := time.NewTicker(flushInterval)
ws = &bufferWriterSyncer{
bufferWriter: bufio.NewWriterSize(ws, bufferSize),
ticker: ticker,
}
go func() {
defer ticker.Stop()
for {
select {
case <-ticker.C:
_ = ws.Sync()
case <-ctx.Done():
return
}
}
}()
closeFunc := func() error {
cancel()
return ws.Sync()
}
return ws, closeFunc
}
func (s *bufferWriterSyncer) Write(bs []byte) (int, error) {
s.Lock()
defer s.Unlock()
if len(bs) > s.bufferWriter.Available() && s.bufferWriter.Buffered() > 0 {
if err := s.bufferWriter.Flush(); err != nil {
return 0, err
}
}
return s.bufferWriter.Write(bs)
}
func (s *bufferWriterSyncer) Sync() error {
s.Lock()
defer s.Unlock()
return s.bufferWriter.Flush()
}