-
Notifications
You must be signed in to change notification settings - Fork 0
/
logstream.go
75 lines (60 loc) · 1.16 KB
/
logstream.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
package main
import (
"bufio"
"context"
"fmt"
"io"
"os"
"time"
)
const (
checkDelay = time.Millisecond * 300
)
type logStreamer struct {
ctx context.Context
f *os.File
err error
pos int64
parser *logParser
}
func newLogStreamer(ctx context.Context, f *os.File, parser *logParser) (*logStreamer, error) {
r := &logStreamer{
ctx: ctx,
f: f,
parser: parser,
}
stat, err := f.Stat()
if err != nil {
return nil, fmt.Errorf("cannot stat log: %w", err)
}
r.pos = stat.Size()
_, err = f.Seek(r.pos, io.SeekStart)
if err != nil {
return nil, fmt.Errorf("cannot seek to %d: %w", r.pos, err)
}
return r, nil
}
func (r *logStreamer) C() <-chan *logLine {
c := make(chan *logLine)
go func(logChan chan *logLine) {
defer func() {
close(logChan)
}()
for {
scanner := bufio.NewScanner(r.f)
for scanner.Scan() {
s := scanner.Text()
log := r.parser.Parse(s)
logChan <- log
}
if scanErr := scanner.Err(); scanErr != nil {
r.err = fmt.Errorf("cannot scan line from log buffer: %w", scanErr)
}
time.Sleep(checkDelay)
}
}(c)
return c
}
func (r *logStreamer) Err() error {
return r.err
}