簡體   English   中英

使用節點 js 獲取特定日期范圍內的 cloudwatch 日志

[英]Fetch cloudwatch log using node js for a specific date range

我想獲取日期為 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 中運行相同的查詢,它會給我一些響應。 我究竟做錯了什么?

您應該檢查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)}`);

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM