-
Notifications
You must be signed in to change notification settings - Fork 11
/
Copy pathcwlogger.go
317 lines (277 loc) · 7.39 KB
/
cwlogger.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
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
package cwlogger
import (
"crypto/rand"
"encoding/hex"
"encoding/json"
"errors"
"net/http"
"strconv"
"sync"
"time"
"github.com/aws/aws-sdk-go/aws"
"github.com/aws/aws-sdk-go/aws/awserr"
"github.com/aws/aws-sdk-go/service/cloudwatchlogs"
)
// The Config for the Logger.
type Config struct {
// The Amazon CloudWatch Logs client created with the AWS SDK for Go.
// Required.
Client *cloudwatchlogs.CloudWatchLogs
// The name of the log group to write logs into. Required.
LogGroupName string
// An optional function to report errors that couldn't be automatically
// handled during a PutLogEvents API call and caused a log events to be
// dropped.
ErrorReporter func(err error)
// An optional log group retention time in days. This value is only taken into
// account when creating a log group that does not yet exist. Set to 0
// (default) for no retention policy. Refer to the PutRetentionPolicy API
// documentation for valid values.
Retention int
}
// A Logger represents a single CloudWatch Logs log group.
type Logger struct {
name *string
svc *cloudwatchlogs.CloudWatchLogs
streams *logStreams
prefix string
batcher *batcher
wg sync.WaitGroup
done chan bool
errorReporter func(err error)
retention int
}
// New creates a new Logger.
//
// Creates the log group if it doesn't yet exist, and one initial log stream for
// writing logs into.
//
// Returns an error if the configuration is invalid, or if either the creation
// of the log group or log stream fail.
func New(config *Config) (*Logger, error) {
if config.Client == nil {
return nil, errors.New("cwlogger: config missing required Client")
}
if config.LogGroupName == "" {
return nil, errors.New("cwlogger: config missing required LogGroupName")
}
errorReporter := noopErrorReporter
if config.ErrorReporter != nil {
errorReporter = config.ErrorReporter
}
lg := &Logger{
errorReporter: errorReporter,
name: &config.LogGroupName,
svc: config.Client,
retention: config.Retention,
prefix: randomHex(32),
batcher: newBatcher(),
done: make(chan bool),
}
lg.streams = newLogStreams(lg)
if err := lg.createIfNotExists(); err != nil {
return nil, err
}
if err := lg.streams.new(); err != nil {
return nil, err
}
go lg.worker()
return lg, nil
}
// Log enqueues a log message to be written to a log stream.
//
// The log message must be less than 1,048,550 bytes, and the time must not be
// more than 2 hours in the future, 14 days in the past, or older than the
// retention period of the log group.
//
// This method is safe for concurrent access by multiple goroutines.
func (lg *Logger) Log(t time.Time, s string) {
lg.wg.Add(1)
go func() {
lg.batcher.input <- &cloudwatchlogs.InputLogEvent{
Message: &s,
Timestamp: aws.Int64(t.UnixNano() / int64(time.Millisecond)),
}
lg.wg.Done()
}()
}
// Close drains all enqueued log messages and writes them to CloudWatch Logs.
// This method blocks until all pending log messages are written.
//
// The Logger is not meant to be used anymore after this method is called.
// Doing so will result in a panic. Create a new Logger if you wish to write
// more logs.
func (lg *Logger) Close() {
lg.wg.Wait() // wait for all log entries to be accepted
lg.batcher.flush() // wait for all log entries to be batched
<-lg.done // wait for all batches to be processed
lg.streams.flush() // wait for all batches to be sent to CloudWatch Logs
}
func (lg *Logger) worker() {
for batch := range lg.batcher.output {
lg.streams.write(batch)
}
lg.done <- true
}
func (lg *Logger) createIfNotExists() error {
_, err := lg.svc.CreateLogGroup(&cloudwatchlogs.CreateLogGroupInput{
LogGroupName: lg.name,
})
if err != nil {
if awsErr, ok := err.(awserr.Error); ok {
if awsErr.Code() == cloudwatchlogs.ErrCodeResourceAlreadyExistsException {
return nil
}
}
}
if lg.retention != 0 {
_, err = lg.svc.PutRetentionPolicy(&cloudwatchlogs.PutRetentionPolicyInput{
LogGroupName: lg.name,
RetentionInDays: aws.Int64(int64(lg.retention)),
})
}
return err
}
type writeError struct {
batch []*cloudwatchlogs.InputLogEvent
stream *logStream
err error
}
type logStreams struct {
logger *Logger
streams []*logStream
writers map[*logStream]chan []*cloudwatchlogs.InputLogEvent
writes chan []*cloudwatchlogs.InputLogEvent
errors chan *writeError
wg sync.WaitGroup
}
func newLogStreams(lg *Logger) *logStreams {
streams := &logStreams{
logger: lg,
streams: []*logStream{},
writers: make(map[*logStream]chan []*cloudwatchlogs.InputLogEvent),
writes: make(chan []*cloudwatchlogs.InputLogEvent),
errors: make(chan *writeError),
}
go streams.coordinator()
return streams
}
func (ls *logStreams) new() error {
name := ls.logger.prefix + "." + strconv.Itoa(len(ls.streams))
stream := &logStream{
name: &name,
logger: ls.logger,
}
err := stream.create()
if err != nil {
return err
}
ls.streams = append(ls.streams, stream)
ls.writers[stream] = make(chan []*cloudwatchlogs.InputLogEvent)
go ls.writer(stream)
return nil
}
func (ls *logStreams) write(b []*cloudwatchlogs.InputLogEvent) {
ls.wg.Add(1)
go func() {
ls.writes <- b
}()
}
func (ls *logStreams) writer(stream *logStream) {
for batch := range ls.writers[stream] {
batch := batch // create new instance of batch for the goroutine
err := stream.write(batch)
if err != nil {
go func() {
ls.errors <- &writeError{
batch: batch,
stream: stream,
err: err,
}
}()
} else {
ls.wg.Done()
}
}
}
func (ls *logStreams) coordinator() {
i := 0
for {
select {
case batch := <-ls.writes:
i = (i + 1) % len(ls.streams)
stream := ls.streams[i]
ls.writers[stream] <- batch
case err := <-ls.errors:
ls.handle(err)
}
}
}
func (ls *logStreams) handle(writeErr *writeError) {
if isErrorCode(writeErr.err, errCodeThrottlingException) {
ls.new()
}
if shouldRetry(writeErr.err) {
go func() {
ls.writes <- writeErr.batch
}()
} else {
ls.wg.Done()
ls.logger.errorReporter(writeErr.err)
}
}
func (ls *logStreams) flush() {
ls.wg.Wait()
}
type logStream struct {
name *string
logger *Logger
sequenceToken *string
}
func (ls *logStream) create() error {
_, err := ls.logger.svc.CreateLogStream(&cloudwatchlogs.CreateLogStreamInput{
LogGroupName: ls.logger.name,
LogStreamName: ls.name,
})
return err
}
func (ls *logStream) write(b []*cloudwatchlogs.InputLogEvent) error {
req, _ := ls.logger.svc.PutLogEventsRequest(&cloudwatchlogs.PutLogEventsInput{
LogGroupName: ls.logger.name,
LogStreamName: ls.name,
LogEvents: b,
SequenceToken: ls.sequenceToken,
})
req.Sign()
resp, err := ls.logger.svc.Client.Config.HTTPClient.Do(req.HTTPRequest)
if err != nil {
return err
}
dec := json.NewDecoder(resp.Body)
defer resp.Body.Close()
if resp.StatusCode == http.StatusOK {
var data putLogEventsSuccessResponse
if err := dec.Decode(&data); err != nil {
return err
}
ls.sequenceToken = &data.NextSequenceToken
} else {
var data putLogEventsErrorResponse
if err := dec.Decode(&data); err != nil {
return err
}
if data.ExpectedSequenceToken != nil {
ls.sequenceToken = data.ExpectedSequenceToken
}
return Error{
Code: data.Code,
Message: data.Message,
}
}
return nil
}
func randomHex(n int) string {
b := make([]byte, n)
rand.Read(b)
return hex.EncodeToString(b)
}