Skip to content

Instantly share code, notes, and snippets.

@zenoyu
Last active March 28, 2024 19:28
Show Gist options
  • Save zenoyu/f63799a9079a5df376d5daf3cea27be4 to your computer and use it in GitHub Desktop.
Save zenoyu/f63799a9079a5df376d5daf3cea27be4 to your computer and use it in GitHub Desktop.
AWS Lambda (Node) - Using Insight API to Query your Cloudwatch Log for Daily Error Report
/**
* AWS Lambda (Node) - Using Insight API to Query your Cloudwatch Log for Daily Error Report
* @author Zeno Yu <zeno.yu@gmail.com>
*/
const AWS = require('aws-sdk');
var cloudwatchlogs = new AWS.CloudWatchLogs();
exports.handler = async (event) => {
// Cloudwatch Log Group name
const logGroupName = '/aws/lambda/<Name of your Log Group>';
const timestamp = new Date();
const params = {
endTime: timestamp.getTime(),
queryString: `fields @message, @timestamp
| sort @timestamp desc
| limit 10
| filter @message like /(?i)("Error")/
| stats count() by bin(1d)`, // Group by Day
startTime: timestamp.setDate( timestamp.getDate() - 3 ), // Last 3 days
logGroupName: logGroupName
};
// 1. Start the query. When we start a query, this returns a queryId for us to use on our next step.
const data = await cloudwatchlogs.startQuery(params).promise();
const { queryId } = data;
console.debug('query id', queryId);
while (true) {
// 2. Send Insight query to CloudwatchLogs
const insightData = await cloudwatchlogs.getQueryResults({ queryId })
.promise();
// 3. Check if it is available
if (Array.isArray(insightData.results) && insightData.status === 'Complete') {
const insightResult = insightData.results;
// Change this line to publish to SNS or send to Slack
console.log(JSON.stringify(insightResult, null, 4))
break;
}
// 4. Otherwise, Wait for 100 ms for insight api result
await new Promise((resolve, reject) => setTimeout(resolve, 100));
}
return 'ok';
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment