Created
February 2, 2022 14:04
-
-
Save perryraskin/967462f630b3f778879df7d396dbdb84 to your computer and use it in GitHub Desktop.
Get live logs from AWS CloudWatch
This file contains 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
var AWS = require("aws-sdk"); | |
AWS.config.update({ | |
region: "us-west-2", | |
}); | |
const { | |
CloudWatchLogsClient, | |
AssociateKmsKeyCommand, | |
StartQueryCommand, | |
GetQueryResultsCommand, | |
} = require("@aws-sdk/client-cloudwatch-logs"); | |
var dayjs = require("dayjs"); | |
// Create CloudWatch service object | |
var cw = new AWS.CloudWatch({ | |
apiVersion: "2010-08-01", | |
}); | |
let currentQueryId = ""; | |
const client = new CloudWatchLogsClient({ region: "us-west-2" }); | |
async function startQuery() { | |
const params = { | |
startTime: dayjs("2022-01-20").unix(), | |
endTime: dayjs().unix(), | |
logGroupNames: ["GROUP_NAME"], | |
queryString: ` | |
fields @timestamp, @message | |
| sort @timestamp desc | |
| limit 20 | |
`, | |
}; | |
const cmd = new StartQueryCommand(params); | |
// console.log(cmd); | |
const response = await client.send(cmd); | |
// console.log(response); | |
return response; | |
} | |
async function getQueryResults(queryId) { | |
const results = new GetQueryResultsCommand({ | |
queryId: queryId, | |
}); | |
const resultsResponse = await client.send(results); | |
if (resultsResponse.results[0]) { | |
currentQueryId = queryId; | |
console.log( | |
resultsResponse.results[0].find((x) => x.field === "@timestamp").value | |
); | |
console.log( | |
resultsResponse.results[0].find((x) => x.field === "@message").value | |
); | |
} else console.log("No results found"); | |
} | |
setInterval(async () => { | |
const { queryId } = await startQuery(); | |
console.log(queryId); | |
setInterval(async () => { | |
if (currentQueryId !== queryId) getQueryResults(queryId); | |
}, 1000); | |
}, 10000); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment