-
Notifications
You must be signed in to change notification settings - Fork 13
/
hook.go
246 lines (214 loc) · 5.53 KB
/
hook.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
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
package logrus_cloudwatchlogs
import (
"fmt"
"io"
"os"
"sync"
"time"
"github.com/aws/aws-sdk-go/aws/session"
"github.com/aws/aws-sdk-go/aws"
"github.com/aws/aws-sdk-go/aws/awserr"
"github.com/aws/aws-sdk-go/service/cloudwatchlogs"
"github.com/sirupsen/logrus"
)
type Hook struct {
svc *cloudwatchlogs.CloudWatchLogs
groupName string
streamName string
nextSequenceToken *string
m sync.Mutex
ch chan *cloudwatchlogs.InputLogEvent
err *error
}
func NewHookWithDuration(groupName, streamName string, sess *session.Session, batchFrequency time.Duration) (*Hook, error) {
return NewBatchingHook(groupName, streamName, sess, batchFrequency)
}
func NewHook(groupName, streamName string, sess *session.Session) (*Hook, error) {
return NewBatchingHook(groupName, streamName, sess, 0)
}
func (h *Hook) getOrCreateCloudWatchLogGroup() (*cloudwatchlogs.DescribeLogStreamsOutput, error) {
resp, err := h.svc.DescribeLogStreams(&cloudwatchlogs.DescribeLogStreamsInput{
LogGroupName: aws.String(h.groupName),
LogStreamNamePrefix: aws.String(h.streamName),
})
if err != nil {
if aerr, ok := err.(awserr.Error); ok {
switch aerr.Code() {
case cloudwatchlogs.ErrCodeResourceNotFoundException:
_, err = h.svc.CreateLogGroup(&cloudwatchlogs.CreateLogGroupInput{
LogGroupName: aws.String(h.groupName),
})
if err != nil {
return nil, err
}
return h.getOrCreateCloudWatchLogGroup()
default:
return nil, err
}
} else {
return nil, err
}
}
return resp, nil
}
func NewBatchingHook(groupName, streamName string, sess *session.Session, batchFrequency time.Duration) (*Hook, error) {
h := &Hook{
svc: cloudwatchlogs.New(sess),
groupName: groupName,
streamName: streamName,
}
resp, err := h.getOrCreateCloudWatchLogGroup()
if err != nil {
return nil, err
}
if batchFrequency > 0 {
h.ch = make(chan *cloudwatchlogs.InputLogEvent, 10000)
go h.putBatches(time.Tick(batchFrequency))
}
// grab the next sequence token
if len(resp.LogStreams) > 0 {
h.nextSequenceToken = resp.LogStreams[0].UploadSequenceToken
return h, nil
}
// create stream if it doesn't exist. the next sequence token will be null
_, err = h.svc.CreateLogStream(&cloudwatchlogs.CreateLogStreamInput{
LogGroupName: aws.String(groupName),
LogStreamName: aws.String(streamName),
})
if err != nil {
return nil, err
}
return h, nil
}
func (h *Hook) Fire(entry *logrus.Entry) error {
line, err := entry.String()
if err != nil {
fmt.Fprintf(os.Stderr, "Unable to read entry, %v", err)
return err
}
switch entry.Level {
case logrus.PanicLevel:
fallthrough
case logrus.FatalLevel:
fallthrough
case logrus.ErrorLevel:
fallthrough
case logrus.WarnLevel:
fallthrough
case logrus.InfoLevel:
fallthrough
case logrus.DebugLevel:
_, err := h.Write([]byte(line))
return err
default:
return nil
}
}
func (h *Hook) putBatches(ticker <-chan time.Time) {
var batch []*cloudwatchlogs.InputLogEvent
size := 0
for {
select {
case p := <-h.ch:
messageSize := len(*p.Message) + 26
if size+messageSize >= 1048576 || len(batch) == 10000 {
go h.sendBatch(batch)
batch = nil
size = 0
}
batch = append(batch, p)
size += messageSize
case <-ticker:
go h.sendBatch(batch)
batch = nil
size = 0
}
}
}
func (h *Hook) sendBatch(batch []*cloudwatchlogs.InputLogEvent) {
h.m.Lock()
defer h.m.Unlock()
if len(batch) == 0 {
return
}
params := &cloudwatchlogs.PutLogEventsInput{
LogEvents: batch,
LogGroupName: aws.String(h.groupName),
LogStreamName: aws.String(h.streamName),
SequenceToken: h.nextSequenceToken,
}
resp, err := h.svc.PutLogEvents(params)
if err != nil {
h.err = &err
} else {
h.nextSequenceToken = resp.NextSequenceToken
}
}
func (h *Hook) Write(p []byte) (n int, err error) {
event := &cloudwatchlogs.InputLogEvent{
Message: aws.String(string(p)),
Timestamp: aws.Int64(int64(time.Nanosecond) * time.Now().UnixNano() / int64(time.Millisecond)),
}
if h.ch != nil {
h.ch <- event
if h.err != nil {
lastErr := h.err
h.err = nil
return 0, fmt.Errorf("%v", *lastErr)
}
return len(p), nil
}
h.m.Lock()
defer h.m.Unlock()
params := &cloudwatchlogs.PutLogEventsInput{
LogEvents: []*cloudwatchlogs.InputLogEvent{event},
LogGroupName: aws.String(h.groupName),
LogStreamName: aws.String(h.streamName),
SequenceToken: h.nextSequenceToken,
}
resp, err := h.svc.PutLogEvents(params)
if err != nil {
return 0, err
}
h.nextSequenceToken = resp.NextSequenceToken
return len(p), nil
}
func (h *Hook) Levels() []logrus.Level {
return []logrus.Level{
logrus.PanicLevel,
logrus.FatalLevel,
logrus.ErrorLevel,
logrus.WarnLevel,
logrus.InfoLevel,
logrus.DebugLevel,
}
}
// WriterHook is a hook that just outputs to an io.Writer.
// This is useful because our formatter outputs the file
// and line where it was called, and the callstack for a hook
// is different from the callstack for just writing to logrus.Logger.Out.
type WriterHook struct {
w io.Writer
}
func NewWriterHook(w io.Writer) *WriterHook {
return &WriterHook{w: w}
}
func (h *WriterHook) Fire(entry *logrus.Entry) error {
line, err := entry.String()
if err != nil {
fmt.Fprintf(os.Stderr, "Unable to read entry, %v", err)
return err
}
_, err = h.w.Write([]byte(line))
return err
}
func (h *WriterHook) Levels() []logrus.Level {
return []logrus.Level{
logrus.PanicLevel,
logrus.FatalLevel,
logrus.ErrorLevel,
logrus.WarnLevel,
logrus.InfoLevel,
logrus.DebugLevel,
}
}