-
Notifications
You must be signed in to change notification settings - Fork 28
/
writer_sink.go
66 lines (54 loc) · 1.37 KB
/
writer_sink.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
package lager
import (
"io"
"sync"
)
// A Sink represents a write destination for a Logger. It provides
// a thread-safe interface for writing logs
type Sink interface {
//Log to the sink. Best effort -- no need to worry about errors.
Log(LogFormat)
}
type writerSink struct {
writer io.Writer
minLogLevel LogLevel
writeL *sync.Mutex
}
func NewWriterSink(writer io.Writer, minLogLevel LogLevel) Sink {
return &writerSink{
writer: writer,
minLogLevel: minLogLevel,
writeL: new(sync.Mutex),
}
}
func (sink *writerSink) Log(log LogFormat) {
if log.LogLevel < sink.minLogLevel {
return
}
// Convert to json outside of critical section to minimize time spent holding lock
message := append(log.ToJSON(), '\n')
sink.writeL.Lock()
sink.writer.Write(message) //nolint:errcheck
sink.writeL.Unlock()
}
type prettySink struct {
writer io.Writer
minLogLevel LogLevel
writeL sync.Mutex
}
func NewPrettySink(writer io.Writer, minLogLevel LogLevel) Sink {
return &prettySink{
writer: writer,
minLogLevel: minLogLevel,
}
}
func (sink *prettySink) Log(log LogFormat) {
if log.LogLevel < sink.minLogLevel {
return
}
// Convert to json outside of critical section to minimize time spent holding lock
message := append(log.toPrettyJSON(), '\n')
sink.writeL.Lock()
sink.writer.Write(message) //nolint:errcheck
sink.writeL.Unlock()
}