-
Notifications
You must be signed in to change notification settings - Fork 42
/
async.go
56 lines (48 loc) · 1.06 KB
/
async.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
package log
import (
"io"
"sync"
)
// AsyncWriter is an io.WriteCloser that writes asynchronously.
type AsyncWriter struct {
// ChannelSize is the size of the data channel, the default size is 1.
ChannelSize uint
// Writer specifies the writer of output.
Writer io.Writer
once sync.Once
ch chan *Entry
chClose chan error
}
// Close implements io.Closer, and closes the underlying Writer.
func (w *AsyncWriter) Close() (err error) {
w.ch <- nil
err = <-w.chClose
return
}
// Write implements io.Writer.
func (w *AsyncWriter) Write(p []byte) (int, error) {
e := epool.Get().(*Entry)
e.buf = append(e.buf[:0], p...)
return w.WriteEntry(e)
}
// WriteEntry implements entryWriter.
func (w *AsyncWriter) WriteEntry(e *Entry) (int, error) {
w.once.Do(func() {
// channels
w.ch = make(chan *Entry, w.ChannelSize)
w.chClose = make(chan error)
go func() {
var err error
for e := range w.ch {
if e == nil {
break
}
_, err = w.Writer.Write(e.buf)
e.Discard()
}
w.chClose <- err
}()
})
w.ch <- e
return len(e.buf), nil
}