使用node js获取特定日期范围的cloudwatch日志

nhjlsmyf  于 2022-12-18  发布在  Node.js
关注(0)|答案(1)|浏览(127)

我想获取日期为2021-08-01到2021-08-16的cloudwatch日志。我使用的代码如下所示:

const params = {
    endTime: 1629072000,
    queryString: 'fields @timestamp, @message|sort @timestamp desc|filter tenant="mediability"',
    startTime: 1627776000,
    limit: 1000,
    logGroupName: 'logGroup',
  };
  const resp = await clg.startQuery(params).promise()
if (resp.queryId) {
    const resp1 = await clg
      .getQueryResults({
        queryId: resp.queryId,
      })
      .promise();
    console.log(resp1);
  }

但是这个返回给我0个结果。但是如果我在aws中运行同样的查询,它会给我一些响应。我做错了什么?

sqxo8psd

sqxo8psd1#

您应该检查resp.status === 'Complete'。我使用了下面的代码,它对我很有效。

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';
}

您可以使用的另一个API是filterLogEvents

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)}`);

相关问题