forked from thrasher-corp/gocryptotrader
-
Notifications
You must be signed in to change notification settings - Fork 0
/
logger_multiwriter.go
74 lines (63 loc) · 1.43 KB
/
logger_multiwriter.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
package log
import (
"io"
)
// Add appends a new writer to the multiwriter slice
func (mw *multiWriter) Add(writer io.Writer) {
mw.mu.Lock()
mw.writers = append(mw.writers, writer)
mw.mu.Unlock()
}
// Remove removes existing writer from multiwriter slice
func (mw *multiWriter) Remove(writer io.Writer) {
mw.mu.Lock()
var removeIDs []int
for i := range mw.writers {
if mw.writers[i] == writer {
removeIDs = append(removeIDs, i)
}
}
for x := range removeIDs {
mw.writers[x] = mw.writers[len(mw.writers)-1]
mw.writers[len(mw.writers)-1] = nil
mw.writers = mw.writers[:len(mw.writers)-1]
}
mw.mu.Unlock()
}
// Write concurrent safe Write for each writer
func (mw *multiWriter) Write(p []byte) (n int, err error) {
type data struct {
n int
err error
}
mw.mu.RLock()
defer mw.mu.RUnlock()
results := make(chan data, len(mw.writers))
for _, wr := range mw.writers {
go func(w io.Writer, p []byte, ch chan data) {
n, err = w.Write(p)
if err != nil {
ch <- data{n, err}
return
}
if n != len(p) {
ch <- data{n, io.ErrShortWrite}
return
}
ch <- data{n, nil}
}(wr, p, results)
}
for range mw.writers {
d := <-results
if d.err != nil {
return d.n, d.err
}
}
return len(p), nil
}
// MultiWriter make and return a new copy of multiWriter
func MultiWriter(writers ...io.Writer) io.Writer {
w := make([]io.Writer, len(writers))
copy(w, writers)
return &multiWriter{writers: w}
}