Node.JS 在 AWS Lambda 中不会将自定义指标数据放入 Cloudwatch
Node.JS in AWS Lambda does not put custom metric data in Cloudwatch
我有以下代码片段
const AWS = require('aws-sdk');
exports.handler = async (event, context) => {
// Set the region
console.log('line1');
AWS.config.update({region: 'cn-north-1'});
console.log('line2');
// Create CloudWatch service object
var cw = new AWS.CloudWatch({apiVersion: '2010-08-01'});
console.log('line3');
//Create parameters JSON for putMetricData
var params = {
MetricData: [
{
MetricName: 'PAGES_VISITED',
Dimensions: [
{
Name: 'UNIQUE_PAGES',
Value: 'URLS'
},
],
Unit: 'None',
Value: 1.0
},
],
Namespace: 'SITE/TRAFFIC'
};
console.log('line4');
if (cw){
console.log('cw is not null');
}else{
console.log('cw is null');
}
cw.putMetricData(params, function(err, data) {
console.log('callback function');
if (err) {
console.log("Error", err);
} else {
console.log("Success", JSON.stringify(data));
}
});
console.log('line5');
return "the result";
};
我在 Lambda 控制台测试后。我可以看到正在创建的那些 Cloudwatch 日志。但是我看不到正在创建的 Cloudwatch 指标。
我已将 Lambda 的角色设置为具有策略 Cloudwatch:PutMetricData
它不起作用的原因是因为您没有回调但已将函数声明为异步。
选项 1:删除第 2 行的 'async' 即可。
exports.handler = (event,context) => {...
选项 2:保持异步,添加回调作为参数,并在 lambda 函数末尾调用回调。
第 2 行需要回调作为参数:
exports.handler = async (event,context,callback) => {...
然后在底部添加:
callback(null, true);
我有以下代码片段
const AWS = require('aws-sdk');
exports.handler = async (event, context) => {
// Set the region
console.log('line1');
AWS.config.update({region: 'cn-north-1'});
console.log('line2');
// Create CloudWatch service object
var cw = new AWS.CloudWatch({apiVersion: '2010-08-01'});
console.log('line3');
//Create parameters JSON for putMetricData
var params = {
MetricData: [
{
MetricName: 'PAGES_VISITED',
Dimensions: [
{
Name: 'UNIQUE_PAGES',
Value: 'URLS'
},
],
Unit: 'None',
Value: 1.0
},
],
Namespace: 'SITE/TRAFFIC'
};
console.log('line4');
if (cw){
console.log('cw is not null');
}else{
console.log('cw is null');
}
cw.putMetricData(params, function(err, data) {
console.log('callback function');
if (err) {
console.log("Error", err);
} else {
console.log("Success", JSON.stringify(data));
}
});
console.log('line5');
return "the result";
};
我在 Lambda 控制台测试后。我可以看到正在创建的那些 Cloudwatch 日志。但是我看不到正在创建的 Cloudwatch 指标。
我已将 Lambda 的角色设置为具有策略 Cloudwatch:PutMetricData
它不起作用的原因是因为您没有回调但已将函数声明为异步。
选项 1:删除第 2 行的 'async' 即可。
exports.handler = (event,context) => {...
选项 2:保持异步,添加回调作为参数,并在 lambda 函数末尾调用回调。 第 2 行需要回调作为参数:
exports.handler = async (event,context,callback) => {...
然后在底部添加:
callback(null, true);