[英]Node.js - How to keep describing Cloudwatch log queries for Completed status of a specific query
So for anyone familiar with CW Logs..this is not the typical DB query call that returns with results.因此,对于任何熟悉 CW 日志的人来说……这不是返回结果的典型数据库查询调用。 You send an API call to start a query, that returns a Query ID.您发送 API 调用以启动查询,该查询返回一个查询 ID。 You then send a different API call to get the query results, with the "hope" that the query completed, and if it hasn't, you're out of luck.然后,您发送一个不同的 API 调用以获取查询结果,并“希望”查询完成,如果没有,那您就不走运了。 That's where I am right now.那就是我现在的位置。
I have a query that takes a bit of time and I'm "guessing" the way to handle this is to keep looping the DescribeQueries call until I find a match among that returned array of Completed queries, then go on with the rest of the code.我有一个查询需要一些时间,我“猜测”处理这个问题的方法是继续循环 DescribeQueries 调用,直到我在返回的已完成查询数组中找到匹配项,然后继续其余的查询代码。 I am unable to pull this off!我无法做到这一点! Grrrr!!呜呜!!
I have tried While and Do..While loops that completely do NOT work.我试过 While 和 Do..While 循环完全不起作用。 I tried setting the escape condition value when a match is found.. but it never gets set and the Lambda function times out.我尝试在找到匹配项时设置转义条件值。但它永远不会设置并且 Lambda 函数超时。
function checkQueryStatus (logGroup, qID, callback) {
var params = {
logGroupName: logGroup,
maxResults: '3',
status: 'Complete'
};
let found = 0;
do {
cwlogs.describeQueries(params, function(err, data) {
if (err) console.log(err, err.stack); // an error occurred
else {
// console.log(data.queries); // successful response
const qList = data.queries;
if (qList.some(query => query.queryId === qID)) {
console.log('Query Done');
callback(1);
found = 1;
} else {
console.log('Query not done');
}
}
});
} while (found == 0);
}
checkQueryStatus(logGroupName, queryID, function(qStatus) {
console.log('Query Status: ', qStatus);
if (qStatus == 1) {
console.log('Query Done');
<do other code...>
How can I do it?我该怎么做? I'm now looking into Promises to see what thats all about.. If the DescribeQueries find a match, I want to trigger the GetQueryResults API call.我现在正在研究 Promises 以了解它的全部内容。如果 DescribeQueries 找到匹配项,我想触发 GetQueryResults API 调用。
I've run into a similar problem with AWS Athena. 我遇到了与AWS Athena类似的问题。 When I start a query, I get back the response that is has started but get no notification when it finishes. 当我开始查询时,我会返回已启动的响应,但在完成时不会收到通知。 The best solution I came up with was to use setTimeout to check its status every 100ms or so and continue when the query is completed. 我想出的最佳解决方案是使用setTimeout每100ms左右检查一次状态,并在查询完成后继续。 Hope that helps. 希望有所帮助。
Here is a generic function which you can use to await until the query finish and returns the query result.这是一个通用函数,您可以使用它等待查询完成并返回查询结果。
async function queryCloudWatch(queryRequest: StartQueryRequest): Promise<GetQueryResultsResponse> {
const queryResponse: StartQueryResponse = await cloudwatchLogs.startQuery(queryRequest).promise()
if (!queryResponse.queryId) return {}
let response: GetQueryResultsResponse | undefined = undefined
while (!response || response.status === 'Running') {
response = await cloudwatchLogs.getQueryResults({
"queryId": queryResponse.queryId
}).promise()
}
return response;
}
You have two options: query log Insights or query log groups您有两个选择:查询日志见解或查询日志组
If you would like to query log Insights:如果您想查询日志 Insights:
const AWS = require('aws-sdk');
AWS.config.setPromisesDependency(require('bluebird'));
AWS.config.update({region: 'us-west-2'});
const cloudWatchLogs = new AWS.CloudWatchLogs({apiVersion: '2014-03-28'});
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';
}
To query log groups use filterLogEvents API:要查询日志组,请使用 filterLogEvents API:
const AWS = require('aws-sdk');
AWS.config.setPromisesDependency(require('bluebird'));
AWS.config.update({region: 'us-west-2'});
const cloudWatchLogs = new AWS.CloudWatchLogs({apiVersion: '2014-03-28'});
const timestamp = new Date();
const endtTime = timestamp.getTime();
const params = {
endTime: endtTime,
filterPattern: `"${stringToSearch}"`,
startTime: new Date (endtTime - 5 * 60 * 60* 24 * 1000).getTime(), // Last 5 days
logGroupName: 'myLogGroup',
limit : 10
};
const events = await cloudWatchLogs.filterLogEvents(params).promise();
console.log(`successfully queryCloudWatchLogs ${stringToSearch} results: ${JSON.stringify(events)}`);
const results = events.events.map(e => e.message)
console.log(`successfully queryCloudWatchLogs ${stringToSearch} results (${results.length}): ${JSON.stringify(results)}`);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.