-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathindex.js
286 lines (237 loc) · 9.33 KB
/
index.js
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
const { CloudWatchLogsClient, CreateLogGroupCommand, CreateLogStreamCommand, PutLogEventsCommand } = require('@aws-sdk/client-cloudwatch-logs');
const truncate = require('truncate-utf8-bytes');
const { Transport } = require('winston');
const Debug = require('debug');
const debugMessages = Debug('CloudWatchTransport:messages');
const debugStats = Debug('CloudWatchTransport:stats');
const debug = Debug('CloudWatchTransport');
// really hard to find docs about winston transports, so inspired by:
// https://github.com/winstonjs/winston/blob/master/lib/winston/transports/file.js
// https://github.com/winstonjs/winston-transport/issues/33
// https://docs.aws.amazon.com/AmazonCloudWatchLogs/latest/APIReference/API_PutLogEvents.html
const maxBatchNumItems = 10000;
const maxMessageNumBytes = 256000; // the real max size is 262144
const maxBatchNumBytes = 1048576;
// An error class when there's no point in trying anymore
class FatalError extends Error {
constructor(cause) {
super('Fatal error');
this.cause = cause;
}
}
const getStringBytesSize = (msg) => Buffer.byteLength(msg, 'utf8');
function defaultGetTimestamp({ timestamp }) {
if (typeof timestamp === 'string') {
const parsed = Date.parse(timestamp);
if (!Number.isNaN(parsed)) return +parsed;
}
// Log calls seem to be delayed when `callback` is not called immediately, thereby delaying timestamps, so this new Date() fallback is not accurate
// but better than nothing
return +new Date();
}
function transport({ client, logGroupName, logStreamName, shouldCreateLogGroup, shouldCreateLogStream, formatLog, onError, onFatalError, minInterval, maxQueuedBatches, abandonQueueOnClose, truncatedMessageSuffix, queueOverrunMessage, getTimestamp }) {
const truncatedMessageSuffixNumBytes = getStringBytesSize(truncatedMessageSuffix);
const batches = [];
let currentBatchTotalMessageSize = 0;
let stopped = false;
let createdLogGroup = false;
let createdLogStream = false;
let queueOverrun = false;
let timeout;
const callbacks = new Set();
async function createLogGroup() {
try {
// https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/client/cloudwatch-logs/command/CreateLogGroupCommand/
await client.send(new CreateLogGroupCommand({
logGroupName,
// todo:
// kmsKeyId,
// tags,
}));
} catch (err) {
if (err.name === 'ResourceAlreadyExistsException') {
// OK
} else if (['InvalidParameterException', 'LimitExceededException', 'UnrecognizedClientException'].includes(err.name)) {
throw new FatalError(err);
} else {
throw err;
}
}
createdLogGroup = true;
}
async function createLogStream() {
try {
// https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/client/cloudwatch-logs/command/CreateLogStreamCommand/
await client.send(new CreateLogStreamCommand({
logGroupName,
logStreamName,
}));
} catch (err) {
if (err.name === 'ResourceAlreadyExistsException') {
// OK
} else if (['InvalidParameterException', 'ResourceNotFoundException', 'UnrecognizedClientException'].includes(err.name)) {
throw new FatalError(err);
} else {
throw err; // retry
}
}
createdLogStream = true;
}
function callCallbacksIfEmptyQueue() {
if (batches.length === 0) { // queue is empty, call the callbacks!
callbacks.forEach((callback) => {
try {
callback();
} catch (err) { /* ignored */ }
});
callbacks.clear();
queueOverrun = false;
}
}
async function processQueue() {
try {
callCallbacksIfEmptyQueue();
const batch = batches.shift();
if (batch == null) return;
try {
if (!createdLogGroup && shouldCreateLogGroup) await createLogGroup();
if (!createdLogStream && shouldCreateLogStream) await createLogStream();
debug('sending batch');
// throw new FatalError(new Error('test'));
try {
// https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/client/cloudwatch-logs/command/PutLogEventsCommand/
const response = await client.send(new PutLogEventsCommand({
logGroupName,
logStreamName,
logEvents: batch,
}));
debug('sent batch');
if (response.rejectedLogEventsInfo != null) onError(new Error('Rejected log events'));
// todo
/* {
tooNewLogEventStartIndex: Number("int"),
tooOldLogEventEndIndex: Number("int"),
expiredLogEventEndIndex: Number("int"),
} */
} catch (err) {
if (err.name === 'DataAlreadyAcceptedException') {
// OK
} else if (['InvalidParameterException', 'InvalidSequenceTokenException', 'ResourceNotFoundException', 'UnrecognizedClientException'].includes(err.name)) {
throw new FatalError(err);
}
throw err; // retry
}
} catch (err) {
if (err instanceof FatalError) {
onFatalError(err.cause);
return;
}
// non-fatal errors: retry forever, in case internet got disconnected temporarily etc
onError(err);
batches.unshift(batch); // put it back for retry
}
} finally {
if (!stopped || !abandonQueueOnClose) timeout = setTimeout(processQueue, minInterval);
}
}
async function log(info) {
let message = formatLog(info);
let messageBytesSize = getStringBytesSize(message);
const timestamp = getTimestamp(info);
if (stopped) {
throw new Error('Tried to log after transport closed');
}
// this is just to prevent memory overrun
if (batches.length >= maxQueuedBatches - 1) {
const err = new Error('Batch queue is full, skipping log message');
if (queueOverrun || !queueOverrunMessage) {
throw err;
}
queueOverrun = true;
onError(err);
message = queueOverrunMessage;
messageBytesSize = getStringBytesSize(message);
}
const actualMaxMessageNumBytes = maxMessageNumBytes - truncatedMessageSuffixNumBytes;
// if we were to send a too long message, we would get InvalidParameterException from AWS
if (messageBytesSize > actualMaxMessageNumBytes) {
onError(new Error(`Truncating log message (${messageBytesSize} bytes)`));
message = `${truncate(message, actualMaxMessageNumBytes)}${truncatedMessageSuffix}`;
messageBytesSize = getStringBytesSize(message);
}
if (batches.length === 0) {
batches.push([]);
currentBatchTotalMessageSize = 0;
}
const batch = batches[batches.length - 1];
batch.push({ timestamp, message });
currentBatchTotalMessageSize += messageBytesSize;
debugMessages(timestamp, message);
debugStats('log message', messageBytesSize, 'bytes', 'batches:', batches.length, 'batchItems:', batch.length, 'batchBytes:', currentBatchTotalMessageSize);
// need to start a new batch?
const maxBatchNumItemsExceeded = batch.length >= maxBatchNumItems;
const maxBatchNumBytesExceeded = currentBatchTotalMessageSize >= maxBatchNumBytes - actualMaxMessageNumBytes;
if (maxBatchNumItemsExceeded || maxBatchNumBytesExceeded) {
batches.push([]);
currentBatchTotalMessageSize = 0;
debug('new batch', { maxBatchNumItemsExceeded, maxBatchNumBytesExceeded });
}
const promise = new Promise((resolve) => callbacks.add(resolve));
callCallbacksIfEmptyQueue();
return promise;
}
function close() {
debug('close');
stopped = true;
clearTimeout(timeout);
}
processQueue();
return { log, close };
}
class CloudWatchTransport extends Transport {
constructor(options) {
super(options);
const {
aws,
logGroupName,
logStreamName,
shouldCreateLogGroup = false,
shouldCreateLogStream = true,
formatLog = ({ level, message }) => `${level}: ${message}`,
minInterval = 2000,
maxQueuedBatches = 100,
abandonQueueOnClose = true,
truncatedMessageSuffix = ' TRUNCATED',
queueOverrunMessage = 'Log queue overrun',
getTimestamp = defaultGetTimestamp,
onError = console.error,
} = options;
// eslint-disable-next-line no-underscore-dangle
this._onError = onError;
const client = new CloudWatchLogsClient(aws);
const onFatalError = (err) => {
try {
this.emit('error', err); // this will cause winston to close the transport
} catch (ignored) { /* ignored */ } // for some reason this.emit('error') also throws the error
onError(err);
};
// eslint-disable-next-line no-underscore-dangle
this._transport = transport({ client, logGroupName, logStreamName, shouldCreateLogGroup, shouldCreateLogStream, formatLog, onError, onFatalError, minInterval, maxQueuedBatches, abandonQueueOnClose, truncatedMessageSuffix, queueOverrunMessage, getTimestamp });
}
close() {
// eslint-disable-next-line no-underscore-dangle
this._transport.close();
}
log(info, cb = () => {}) {
// eslint-disable-next-line no-underscore-dangle
this._transport.log(info).then(() => {
this.emit('logged', info); // not sure about this but it's found in other transports
cb();
}).catch((err) => {
// eslint-disable-next-line no-underscore-dangle
this._onError(err);
cb(); // doesn't seem like this supports an error
});
}
}
module.exports = CloudWatchTransport;