如何在nodejs中使用`aws-sdk`读取cloudwatch日志

问题描述 投票:0回答:3

如何在nodejs中使用

aws-sdk
读取cloudwatch日志?

我不知道如何初始化我的配置,在哪里可以找到我的 cloudwatch 的任何密钥/端点?

有人可以给我一些例子吗?

import AWS from 'aws-sdk'; 
const cwInstance = new AWS.CloudWatchLogs({
  .....?
})
node.js amazon-web-services aws-sdk amazon-cloudwatch
3个回答
3
投票
import AWS from 'aws-sdk'; 

const cloudwatchlogs = new AWS.CloudWatchLogs({apiVersion: '2014-03-28'});
const params = {
  logGroupName: 'STRING_VALUE', /* required */
  logStreamName: 'STRING_VALUE', /* required */
  endTime: 'NUMBER_VALUE',
  limit: 'NUMBER_VALUE',
  nextToken: 'STRING_VALUE',
  startFromHead: true || false,
  startTime: 'NUMBER_VALUE'
};
cloudwatchlogs.getLogEvents(params, function(err, data) {
  if (err) console.log(err, err.stack); // an error occurred
  else     console.log(data);           // successful response
});

有关更多信息,请查看 AWS 文档


3
投票
const AWS = require('aws-sdk');
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)}`);

0
投票
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;
}
© www.soinside.com 2019 - 2024. All rights reserved.