-
Notifications
You must be signed in to change notification settings - Fork 3.3k
/
writer.go
82 lines (70 loc) · 1.35 KB
/
writer.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
package writer
import (
"fmt"
"io"
"strconv"
"strings"
"time"
)
const (
LogEntry = "%s %s\n"
)
type Writer struct {
w io.Writer
sent chan time.Time
interval time.Duration
size int
prevTsLen int
pad string
quit chan struct{}
done chan struct{}
}
func NewWriter(writer io.Writer, sentChan chan time.Time, entryInterval time.Duration, entrySize int) *Writer {
w := &Writer{
w: writer,
sent: sentChan,
interval: entryInterval,
size: entrySize,
prevTsLen: 0,
quit: make(chan struct{}),
done: make(chan struct{}),
}
go w.run()
return w
}
func (w *Writer) Stop() {
if w.quit != nil {
close(w.quit)
<-w.done
w.quit = nil
}
}
func (w *Writer) run() {
t := time.NewTicker(w.interval)
defer func() {
t.Stop()
close(w.done)
}()
for {
select {
case <-t.C:
t := time.Now()
ts := strconv.FormatInt(t.UnixNano(), 10)
tsLen := len(ts)
// I guess some day this could happen????
if w.prevTsLen != tsLen {
var str strings.Builder
// Total line length includes timestamp, white space separator, new line char. Subtract those out
for str.Len() < w.size-tsLen-2 {
str.WriteString("p")
}
w.pad = str.String()
w.prevTsLen = tsLen
}
_, _ = fmt.Fprintf(w.w, LogEntry, ts, w.pad)
w.sent <- t
case <-w.quit:
return
}
}
}