Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Notify CloudWatch Metrics to Slack
var AWS = require('aws-sdk');
var cloudwatch = new AWS.CloudWatch();
exports.handler = function (event, context) {
alarmMetricStatistics("http", event, context);
alarmMetricStatistics("app", event, context);
}
function alarmMetricStatistics(namespace, event, context) {
console.log(`check namespace: ${namespace}`);
cloudwatch.listMetrics({
Namespace: namespace
},
checkMetrics
);
}
function checkMetrics(err, data) {
if (err) { throw err; }
var now = new Date();
for (var metric of data["Metrics"]) {
console.log(`check metric: ${metric["MetricName"]}`);
cloudwatch.getMetricStatistics({
EndTime: now,
StartTime: new Date(now.getTime() - 60 * 1000 * 5),
MetricName: metric["MetricName"],
Namespace: metric["Namespace"],
Period: '60',
Statistics: ['Sum'],
},
function (err, data) {
if (err) { console.log(err, err.stack); }
else { checkMetric(data); }
});
}
}
function checkMetric(data) {
const dp = data["Datapoints"];
if (dp.length > 0) {
console.log(`alarm metric: ${data["Label"]}`);
const sum = dp.map(point => point["Sum"]).reduce(function (prev, current, i, arr) {
return prev + current;
});
const fields = dp.map(point => {
return { title: point["Timestamp"], value: point["Sum"] }
});
slack({
path: process.env.SLACK_PATH,
message: `${data["Label"]}: ${sum} error${sum >= 2 ? 's' : ''} occurred`,
attachments: [{ color: 'warning', fields: fields }]
})
}
}
// ref. https://utano.jp/entry/2018/02/js-lib-slack/
const slack = (params) => {
let https = require('https');
let host = 'hooks.slack.com';
let data = JSON.stringify({ "text": params['message'], "attachments": params['attachments'] });
let options = {
hostname: host,
port: 443,
path: params['path'],
method: 'POST',
headers: {
'Content-Type': 'application/json',
'Content-Length': Buffer.byteLength(data)
}
};
let req = https.request(options, (res) => {
console.log('status code : ' + res.statusCode);
res.setEncoding('utf8');
res.on('data', (d) => {
console.log(d)
});
});
req.on('error', (e) => {
console.error(e)
;
});
req.write(data);
req.end();
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.