【问题标题】:Error while using Cloudwatch GetMetricWidgetImage API in Nodejs在 Nodejs 中使用 Cloudwatch GetMetricWidgetImage API 时出错
【发布时间】:2021-10-15 06:55:27
【问题描述】:

我正在 Node.js 中创建一个 AWS Lambda 函数。我想使用 Cloudwatch GetMetricWidgetImage API 来获取仪表板快照,但似乎我遇到了麻烦。以下是我编写的代码,没有得到任何适当的响应。代码一直执行到 hello1 并且我得到的响应为空。

console.log('Loading function');

const aws = require('aws-sdk');
var cloudwatch = new aws.CloudWatch({apiVersion: '2010-08-01'});

console.log("hello");

exports.handler = async (event, context, callback) =>{
var widgetDefinition = {
    MetricWidget: '[ "AWS/IVS", "ConcurrentViews" ]',
    OutputFormat: 'image.png'
};

console.log("hello1");

cloudwatch.getMetricWidgetImage(widgetDefinition, function(err, data) { 
  if (err) {
    console.log(err, err.stack) ;                //error occured
    //console.log("hello2");
  }
        else {
            console.log(data.MetricWidgetImage); // successful 
            var response = {
                statusCode: 200,
                body: new Buffer(data.MetricWidgetImage).toString('base64')
                
    };
          console.log(response);
        }
});

};

【问题讨论】:

    标签: javascript amazon-web-services aws-lambda amazon-cloudwatch


    【解决方案1】:

    这里有几个问题。

    首先,确保 lambda 具有调用 GetMetricWidgetImage 的权限。

    那么这是获取widgetDefinition的方法:

    1. 在 CloudWatch 控制台中打开图表。
    2. 点击来源标签。
    3. 选择 Image api 视图并从那里复制代码。

    像这样使用您选择的代码(您的地区可能不同):

    var image = {
        "view": "timeSeries",
        "stacked": false,
        "metrics": [
            [ "AWS/Events", "FailedInvocations" ]
        ],
        "region": "us-east-1"
    }
    
    var widgetDefinition = {
        MetricWidget: JSON.stringify(image)
    };
    

    那么你需要等待 GMWI 的承诺。您的 lambda 在 API 响应之前返回。

    const response = await cloudwatch.getMetricWidgetImage(widgetDefinition).promise();
    

    另外,GMWI 返回一个缓冲区,所以你不应该再次转换为缓冲区。

    把它们放在一起:

    const aws = require('aws-sdk');
    const cloudwatch = new aws.CloudWatch({apiVersion: '2010-08-01'});
    
    const image = {
        "view": "timeSeries",
        "stacked": false,
        "metrics": [
            [ "AWS/Events", "FailedInvocations" ]
        ],
        "region": "us-east-1"
    }
    
    exports.handler = async (event, context, callback) =>{
        const widgetDefinition = {
            MetricWidget: JSON.stringify(image)
        };
        
        const response = await cloudwatch.getMetricWidgetImage(widgetDefinition).promise();
        
        return {
            statusCode: 200,
            body: response.MetricWidgetImage.toString('base64')
        }
    };
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-07-30
      • 2012-04-28
      • 2015-05-31
      • 2017-06-03
      • 1970-01-01
      • 2016-04-07
      相关资源
      最近更新 更多