-
Notifications
You must be signed in to change notification settings - Fork 16
/
sync_logger.go
84 lines (67 loc) · 1.21 KB
/
sync_logger.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
75
76
77
78
79
80
81
82
83
84
package waterwheel
import (
"io"
"sync"
"time"
)
type SyncLogger struct {
wc io.WriteCloser
sync.Mutex
level Level
f Formatter
buf []byte
closed bool
}
func (l *SyncLogger) Level() Level {
return l.level
}
func NewSyncLogger(w io.WriteCloser, f Formatter, lvl string) *SyncLogger {
return &SyncLogger{
wc: w,
level: MapLevel(lvl),
f: f,
buf: []byte{},
}
}
func (l *SyncLogger) Close() error {
l.Lock()
defer l.Unlock()
if l.closed {
return nil
}
l.closed = true
return l.wc.Close()
}
func (l *SyncLogger) Log(lvl Level, msg string) (err error) {
if lvl <= l.level {
l.Lock()
defer l.Unlock()
if l.closed {
return CloseErr
}
l.buf = l.buf[:0]
l.f(&Record{
Level: lvl,
Time: time.Now(),
Message: msg,
}, &l.buf)
_, err := l.wc.Write(l.buf)
return err
}
return nil
}
func (l *SyncLogger) Critical(msg string) error {
return l.Log(Critical, msg)
}
func (l *SyncLogger) Error(msg string) error {
return l.Log(Error, msg)
}
func (l *SyncLogger) Warn(msg string) error {
return l.Log(Warn, msg)
}
func (l *SyncLogger) Info(msg string) error {
return l.Log(Info, msg)
}
func (l *SyncLogger) Debug(msg string) error {
return l.Log(Debug, msg)
}