forked from kubernetes/kubernetes
-
Notifications
You must be signed in to change notification settings - Fork 2
/
log_writer.go
52 lines (42 loc) · 873 Bytes
/
log_writer.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
package testrunner
import (
"bytes"
"fmt"
"io"
"log"
"strings"
"sync"
)
type logWriter struct {
buffer *bytes.Buffer
lock *sync.Mutex
log *log.Logger
}
func newLogWriter(target io.Writer, node int) *logWriter {
return &logWriter{
buffer: &bytes.Buffer{},
lock: &sync.Mutex{},
log: log.New(target, fmt.Sprintf("[%d] ", node), 0),
}
}
func (w *logWriter) Write(data []byte) (n int, err error) {
w.lock.Lock()
defer w.lock.Unlock()
w.buffer.Write(data)
contents := w.buffer.String()
lines := strings.Split(contents, "\n")
for _, line := range lines[0 : len(lines)-1] {
w.log.Println(line)
}
w.buffer.Reset()
w.buffer.Write([]byte(lines[len(lines)-1]))
return len(data), nil
}
func (w *logWriter) Close() error {
w.lock.Lock()
defer w.lock.Unlock()
if w.buffer.Len() > 0 {
w.log.Println(w.buffer.String())
}
return nil
}