forked from kdar/logrus-cloudwatchlogs
/
hook.go
230 lines (199 loc) · 5.41 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
package logrus_cloudwatchlogs
import (
"fmt"
"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
fields logrus.Fields
formatter logrus.Formatter
}
// NewHook returns a new CloudWatch hook.
//
// CloudWatch log events are sent in batches on an interval, batchFrequency. Pass 0 to send events synchronously.
func NewHook(groupName, streamName string, sess *session.Session, batchFrequency time.Duration) (*Hook, error) {
h := &Hook{
svc: cloudwatchlogs.New(sess),
groupName: groupName,
streamName: streamName,
}
var err error
h.nextSequenceToken, err = h.getNextSequenceToken()
if err != nil {
return nil, err
}
if batchFrequency > 0 {
h.ch = make(chan *cloudwatchlogs.InputLogEvent, 10000)
go h.putBatches(time.NewTicker(batchFrequency).C)
}
return h, nil
}
// WithFields includes the given fields to log entries sent to CloudWatch.
func (h *Hook) WithFields(fields logrus.Fields) *Hook {
h.fields = fields
return h
}
// WithFormatter uses the given formatter to format log entries sent to CloudWatch.
func (h *Hook) WithFormatter(formatter logrus.Formatter) *Hook {
h.formatter = formatter
return h
}
// Fire sends the given entry to CloudWatch.
func (h *Hook) Fire(entry *logrus.Entry) error {
if h.fields != nil {
// WithFields() resets the entry. Ensure that we pass data that gets reset.
oldEntry := entry
entry = entry.WithFields(h.fields)
entry.Buffer = oldEntry.Buffer
entry.Caller = oldEntry.Caller
entry.Level = oldEntry.Level
entry.Message = oldEntry.Message
}
var line string
var err error
if h.formatter != nil {
var b []byte
b, err = h.formatter.Format(entry)
line = string(b)
} else {
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
}
}
// Write sends the given bytes to CloudWatch.
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)),
}
// Batching hook - send event via channel
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
}
// Synchronous hook - send event immediately
h.sendBatch([]*cloudwatchlogs.InputLogEvent{event})
return len(p), nil
}
// Returns the next sequence token for the log stream.
// Creates the log group and log stream if they don't exist.
func (h *Hook) getNextSequenceToken() (*string, error) {
resp, err := h.svc.DescribeLogStreams(&cloudwatchlogs.DescribeLogStreamsInput{
LogGroupName: aws.String(h.groupName),
LogStreamNamePrefix: aws.String(h.streamName),
})
// Create log group if it doesn't exist
aerr, ok := err.(awserr.Error)
if ok && aerr.Code() == cloudwatchlogs.ErrCodeResourceNotFoundException {
_, err = h.svc.CreateLogGroup(&cloudwatchlogs.CreateLogGroupInput{
LogGroupName: aws.String(h.groupName),
})
if err != nil {
return nil, err
}
return h.getNextSequenceToken()
}
// Grab the next sequence token
if len(resp.LogStreams) > 0 {
return resp.LogStreams[0].UploadSequenceToken, nil
}
// Create stream if it doesn't exist. The next sequence token will be null
_, err = h.svc.CreateLogStream(&cloudwatchlogs.CreateLogStreamInput{
LogGroupName: aws.String(h.groupName),
LogStreamName: aws.String(h.streamName),
})
if err != nil {
return nil, err
}
return h.getNextSequenceToken()
}
// A goroutine to send log batches on a regular interval.
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
}
}
}
// Sends a batch of logs to cloudwatch.
func (h *Hook) sendBatch(batch []*cloudwatchlogs.InputLogEvent) {
if len(batch) == 0 {
return
}
h.m.Lock()
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.nextSequenceToken = resp.NextSequenceToken
h.m.Unlock()
return
}
h.err = &err
if aerr, ok := err.(*cloudwatchlogs.InvalidSequenceTokenException); ok {
h.nextSequenceToken = aerr.ExpectedSequenceToken
h.m.Unlock()
h.sendBatch(batch)
return
}
h.m.Unlock()
}
func (h *Hook) Levels() []logrus.Level {
return logrus.AllLevels
}