Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Node.js Lambda to decompress and parse Cloudwatch Log Event gzipped data and send to Slack
// In this scenario - a Cloudwatch Subscription Filter is hooked up to a Node.js lambda's ARN
// (see AWS docs around Log Group subscription filters)
// Will need a webhook for the appropriate Slack channel
const https = require('https');
const zlib = require('zlib');
const options = {
hostname: 'hooks.slack.com',
path: 'SLACK_WEBHOOK_URL',
method: 'POST',
headers: {
'Content-Type': 'application/json'
}
};
function decryptCloudwatchGzip(cw){
// write string to buffer
const cwBuffer = Buffer.from(cw, 'base64');
return new Promise(resolve => {
let res = null;
zlib.unzip(cwBuffer, (err, result) => {
if (err){
res = "Error occurred when attempting to unzip the Gzipped log data.\n" + JSON.stringify(err) + "\nOriginalEventData:\n-----" + JSON.stringify(cw);
} else {
const parsedResponse = JSON.parse(result);
const messages = [];
parsedResponse.logEvents.forEach(logEvent => {
if (logEvent.message.toLowerCase().includes('error')){
messages.push(":bangbang: " + logEvent.message);
}
});
res = messages.length > 0 ? messages.join('\n') : null;
}
resolve(res);
});
})
}
exports.handler = async (event) => {
let text = "Event occurred, but no message was retrieved by the Lambda function.";
if (event && event.awslogs){
text = await decryptCloudwatchGzip(event.awslogs.data);
// return if decrypt method returns null - means log message was not an error
if (!text) return;
} else if (event){
text = JSON.stringify(event);
}
const data = JSON.stringify({ text: text });
return new Promise((resolve, reject) => {
const req = https.request(options, (res) => {
resolve('Success');
});
req.on('error', (e) => {
reject(e.message);
});
req.write(data);
req.end();
});
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment