/
accumulator.go
115 lines (101 loc) · 2.52 KB
/
accumulator.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
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
package logger
import (
"fmt"
"io"
"sync"
"time"
)
// Represents a logging priority.
// Logging priorities map to the Debugf, Infof, Warnf, and Errorf printers.
type Priority int
const (
DebugPriority Priority = iota
InfoPriority
WarnPriority
ErrorPriority
)
// Event represents something that was logged.
type Event struct {
Time time.Time
Priority Priority
Message string
}
// Proxy is a simple logger that as long as it is passed by pointer, allows to change
// the underlying logger implementation.
//
// This allows to initialize some code to use a logging object, to then replace it later
// after the initialization stage.
type Proxy struct {
Logger
}
func (p *Proxy) Replace(newl Logger) {
f, ok := p.Logger.(Forwardable)
if ok {
f.Forward(newl)
}
p.Logger = newl
}
// Accumulator is a thread safe object implementing the Logger interface that
// accumulates all messages being logged.
//
// You can then use the Retrieve() or Forward() methods to access or print the
// accumulated messages.
type Accumulator struct {
lock sync.Mutex
event []Event
}
func PrintEvent(ev *Event, log Logger) {
switch ev.Priority {
case InfoPriority:
log.Infof("%s", ev.Message)
case WarnPriority:
log.Warnf("%s", ev.Message)
case DebugPriority:
log.Debugf("%s", ev.Message)
case ErrorPriority:
log.Errorf("%s", ev.Message)
}
}
func (dl *Accumulator) Forward(log Logger) {
dl.ForwardWithPrinter(log, PrintEvent)
}
func (dl *Accumulator) ForwardWithPrinter(log Logger, printer func(*Event, Logger)) {
events := dl.Retrieve()
for _, ev := range events {
printer(&ev, log)
}
}
func (dl *Accumulator) Retrieve() []Event {
dl.lock.Lock()
defer dl.lock.Unlock()
events := dl.event
dl.event = nil
return events
}
func (dl *Accumulator) Add(prio Priority, format string, args ...interface{}) {
dl.lock.Lock()
defer dl.lock.Unlock()
message := fmt.Sprintf(format, args...)
dl.event = append(dl.event, Event{
Priority: prio,
Message: message,
Time: time.Now(),
})
}
func (dl *Accumulator) Debugf(format string, args ...interface{}) {
dl.Add(DebugPriority, format, args...)
}
func (dl *Accumulator) Infof(format string, args ...interface{}) {
dl.Add(InfoPriority, format, args...)
}
func (dl *Accumulator) Errorf(format string, args ...interface{}) {
dl.Add(ErrorPriority, format, args...)
}
func (dl *Accumulator) Warnf(format string, args ...interface{}) {
dl.Add(WarnPriority, format, args...)
}
func (dl *Accumulator) SetOutput(writer io.Writer) {
}
func NewAccumulator() *Accumulator {
return &Accumulator{}
}