/
linelogger.go
43 lines (37 loc) · 964 Bytes
/
linelogger.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
package mlabtest
import (
"bufio"
"fmt"
"io"
"testing"
)
// LogFunc is a type of function used to log lines of output
type LogFunc func(string)
// NewLineLogger allow to log lines of output produced by MLab containers
// It create an io.WriteCloser that parses the output
// into line and send them to the specified function.
func NewLineLogger(f LogFunc) io.WriteCloser {
pr, pw := io.Pipe()
go func() {
scanner := bufio.NewScanner(pr)
for scanner.Scan() {
f(scanner.Text())
}
pr.Close()
pw.Close()
}()
return pw
}
// DefaultLogger create a "default" logging function
// If one is givven it is used as is,
// If not one is built, with the testing object if given, and with stdout
// otherwize
func DefaultLogger(tb testing.TB, prefix string, logger LogFunc) LogFunc {
if logger != nil {
return logger
}
if tb != nil {
return func(line string) { tb.Log(prefix, line) }
}
return func(line string) { fmt.Println(prefix, line) }
}