-
Notifications
You must be signed in to change notification settings - Fork 1
/
divert.go
67 lines (53 loc) · 1.02 KB
/
divert.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
package log
import (
"github.com/hephbuild/heph/log/liblog"
"sync"
)
func newDivertCore(core liblog.Core) *divertCore {
return &divertCore{
core: core,
}
}
type divertCore struct {
core liblog.Core
m sync.Mutex
ch chan liblog.Entry
chDone chan struct{}
}
func (t *divertCore) Enabled(l liblog.Level) bool {
return t.core.Enabled(l)
}
func (t *divertCore) divert(ch chan liblog.Entry) {
t.m.Lock()
defer t.m.Unlock()
t.ch = ch
if t.chDone != nil {
close(t.chDone)
t.chDone = nil
}
if ch != nil {
t.chDone = make(chan struct{})
}
}
func (t *divertCore) Log(entry liblog.Entry) error {
t.m.Lock()
ch, chDone := t.ch, t.chDone
t.m.Unlock()
if ch != nil {
select {
case ch <- entry:
// Successfully diverted
return nil
case <-chDone:
// Another diversion is in place, try again
if t.ch != nil {
return t.Log(entry)
}
t.m.Lock()
defer t.m.Unlock()
// Diversion over, continue as usual...
}
}
return t.core.Log(entry)
}
var _ liblog.Core = (*divertCore)(nil)