-
Notifications
You must be signed in to change notification settings - Fork 18
/
Copy pathlog.go
60 lines (53 loc) · 970 Bytes
/
log.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
package main
import (
"bufio"
"fmt"
"io"
"log"
"strings"
"sync"
)
// DebugLog provides a logger which allows filtering of [DEBUG] log messages
type DebugLog struct {
Logger *log.Logger
out io.Writer
r *io.PipeReader
debug bool
mux sync.Mutex
}
func NewDebugLog(out io.Writer, prefix string, flag int) *DebugLog {
r, w := io.Pipe()
logger := log.New(w, prefix, flag)
l := &DebugLog{
Logger: logger,
out: out,
r: r,
}
go l.filter("[DEBUG]")
return l
}
func (l *DebugLog) SetDebug(d bool) {
l.mux.Lock()
defer l.mux.Unlock()
l.debug = d
}
func (l *DebugLog) Debug() bool {
l.mux.Lock()
defer l.mux.Unlock()
return l.debug
}
func (l *DebugLog) Close() {
l.r.Close()
if c, ok := l.out.(io.Closer); ok {
c.Close()
}
}
func (l *DebugLog) filter(debugPrefix string) {
s := bufio.NewScanner(l.r)
for s.Scan() {
m := s.Text()
if l.Debug() || !strings.Contains(m, debugPrefix) {
fmt.Fprintln(l.out, m)
}
}
}