forked from heroku/hsup
/
reader.go
47 lines (38 loc) · 1.02 KB
/
reader.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
package shuttle
import (
"bufio"
"io"
"time"
"github.com/rcrowley/go-metrics"
)
// LogLineReader performs the reading of lines from an io.ReadCloser, encapsulating
// lines into a LogLine and emitting them on outbox
type LogLineReader struct {
outbox chan<- LogLine
lineCounter metrics.Counter
}
// NewLogLineReader constructs a new reader with it's own Outbox.
func NewLogLineReader(o chan<- LogLine, m metrics.Registry) LogLineReader {
return LogLineReader{
outbox: o,
lineCounter: metrics.GetOrRegisterCounter("line.count", m),
}
}
// ReadLogLines reads lines from the ReadCloser
func (rdr LogLineReader) ReadLogLines(input io.ReadCloser) error {
rdrIo := bufio.NewReader(input)
for {
line, err := rdrIo.ReadBytes('\n')
currentLogTime := time.Now()
if err != nil {
input.Close()
return err
}
rdr.Enqueue(LogLine{line, currentLogTime})
}
}
// Enqueue a single log line and increment the line counters
func (rdr LogLineReader) Enqueue(ll LogLine) {
rdr.outbox <- ll
rdr.lineCounter.Inc(1)
}