-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.mjs
110 lines (98 loc) · 3.24 KB
/
index.mjs
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
import https from 'https'
import zlib from 'zlib'
const url = process.env.SLACK_INCOMING_WEBHOOK_URL;
export async function handler(input) {
const data = await extract(input.awslogs.data);
if (data.messageType === 'CONTROL_MESSAGE') {
return;
}
console.log(data);
console.log({ received: data.logEvents.length });
await post(generatePayload(transform(data)));
}
export async function extract(data) {
const zippedInput = new Buffer.from(data, 'base64');
return await new Promise(function(resolve, reject){
zlib.gunzip(zippedInput, (error, buffer) => {
if (error) {
reject(error);
return;
}
resolve(JSON.parse(buffer.toString('utf8')));
});
});
};
export function transform(data) {
const logGroup = data.logGroup;
const logStream = data.logStream;
const subscriptionFilters = data.subscriptionFilters;
const map = new Map();
data.logEvents
.map(log => {
try {
return JSON.parse(log.message).message;
} catch (err) {
return log.message;
}
})
.forEach(message => {
map.set(message, (map.get(message) || 0) + 1);
});
const length = Math.max(...Array.from(map.values())).toString().length;
const messages = Array.from(map.entries())
.map(([message,cnt]) => `${cnt.toString().padStart(length)}: ${message}`)
.sort().reverse();
return {logGroup, logStream, subscriptionFilters, messages};
};
export function generatePayload({logGroup, logStream, subscriptionFilters, messages}) {
return {
"attachments": [
{
"color": "#cccccc",
"blocks": [
{
"type": "section",
"text": {
"type": "mrkdwn",
"text": `*${logGroup} | ${logStream} | ${subscriptionFilters.join('.')}*`,
"verbatim": false
}
},
{
"type": "section",
"text": {
"type": "mrkdwn",
"text": `\`\`\`\n${messages.join("\n")}\n\`\`\``,
"verbatim": false
}
}
]
}
]
};
}
export async function post(payload) {
const json = JSON.stringify(payload);
await new Promise((resolve, reject) => {
const options = {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
};
const request = https.request(url, options, (res) => {
let body = '';
res.on('data', (chunk) => body += chunk);
res.on('end', () => {
const response = {
status: res.statusCode,
headers: res.headers,
body: body,
};
console.log({response});
resolve(response);
});
});
request.on('error', (err) => reject(err));
request.write(json);
request.end();
});
}