-
Notifications
You must be signed in to change notification settings - Fork 2
/
watcher.go
94 lines (78 loc) · 2.1 KB
/
watcher.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
package runner
import (
"context"
"errors"
"log"
"time"
"github.com/aws/aws-sdk-go/aws"
logs "github.com/aws/aws-sdk-go/service/cloudwatchlogs"
)
type logWatcher struct {
LogGroup, LogStreamName string
Svc *logs.CloudWatchLogs
Printer func(event *logs.FilteredLogEvent, c context.CancelFunc)
}
func (lw *logWatcher) findStreams() ([]*string, error) {
params := &logs.DescribeLogStreamsInput{
LogGroupName: aws.String(lw.LogGroup),
LogStreamNamePrefix: aws.String(lw.LogStreamName),
Descending: aws.Bool(true),
}
streams := []*string{}
err := lw.Svc.DescribeLogStreamsPages(params, func(page *logs.DescribeLogStreamsOutput, lastPage bool) bool {
for _, stream := range page.LogStreams {
streams = append(streams, stream.LogStreamName)
}
return lastPage
})
return streams, err
}
func (lw *logWatcher) printEventsAfter(ts int64, c context.CancelFunc) (int64, error) {
var streams []*string
var err error
// sometimes the stream takes a while to appear
for i := 0; i < 10; i++ {
streams, err = lw.findStreams()
if err != nil || len(streams) == 0 {
log.Printf("Log stream hasn't started yet")
time.Sleep(time.Second * 2)
}
}
if err != nil {
return ts, err
} else if len(streams) == 0 {
return ts, errors.New("No stream found")
}
filterInput := &logs.FilterLogEventsInput{
LogGroupName: aws.String(lw.LogGroup),
LogStreamNames: streams,
StartTime: aws.Int64(ts + 1),
}
err = lw.Svc.FilterLogEventsPages(filterInput,
func(p *logs.FilterLogEventsOutput, lastPage bool) (shouldContinue bool) {
for _, event := range p.Events {
lw.Printer(event, c)
if *event.Timestamp > ts {
ts = *event.Timestamp
}
}
return lastPage
})
return ts, err
}
func (lw *logWatcher) Watch(ctx context.Context) error {
var after int64
var err error
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
for {
select {
case <-time.After(1 * time.Second):
if after, err = lw.printEventsAfter(after, cancel); err != nil {
return err
}
case <-ctx.Done():
return nil
}
}
}