Created
April 20, 2021 13:59
-
-
Save aflansburg/132ef45a5ad9006469d8286bb99a0ec5 to your computer and use it in GitHub Desktop.
Node.js Lambda to decompress and parse Cloudwatch Log Event gzipped data and send to Slack
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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