如何在Node.js中将AWS lambda发布到云监视度量标准

在lambda内部,我使用定期签入服务来检查服务器结果的值,并且我想将该值发布到AWS cloudwatch作为度量标准来形成线图。

我不能为了我的生活而认为我们是这样做的。 整理AWS文档2个小时无处不在。这甚至有可能吗?

要明确这不是关于lambda的度量 ,这是从lamdba发布的度量。

码:

'use strict'; const https = require('http'); exports.handler = (event, context, callback) => { const now = new Date() const yesterday = new Date(now.toISOString()) yesterday.setTime(now.getTime() - (1000 * 60 * 60 * 24)); // 1 day ago) const params = [ ['limit',0], ['pageStart',0], ['startsOnOrAfter',encodeURIComponent(yesterday.toISOString())], ['startsOnOrBefore',encodeURIComponent(now.toISOString())] ].map(kv => `${kv[0]}=${kv[1]}&`).reduce((s1,s2) => s1.concat(s2)) var uri = `http://service/query?${params}` const req = https.request(uri, (res) => { let body = ''; res.setEncoding('utf8'); res.on('data', (chunk) => body += chunk); res.on('end', () => { if (!res.headers[ 'content-type' ].match('application/.*?json')) { return callback(`unknown content type ${res.headers[ 'content-type' ]}`,body) } body = JSON.parse(body); if(body.total && body.total > 0) { callback(null, body.total); // body.total to form a line chart } else { callback({ message: 'No plans found for time period', uri: uri }) } }); }); req.on('error', callback); req.end(); }; 

是的,这是可能的:

 const AWS = require('aws-sdk'); const metric = { MetricData: [ /* required */ { MetricName: 'YOUR_METRIC_NAME', /* required */ Dimensions: [ { Name: 'URL', /* required */ Value: url /* required */ }, /* more items */ ], Timestamp: new Date(), Unit: 'Count', Value: SOME_VALUE }, /* more items */ ], Namespace: 'YOUR_METRIC_NAMESPACE' /* required */ }; const cloudwatch = new AWS.CloudWatch({region: 'eu-west-1'}); cloudwatch.putMetricData(metric, (err, data) => { if (err) { console.log(err, err.stack); // an error occurred } else { console.log(data); // successful response } }); 

首先,创build要存储为度量标准的数据,然后使用CloudWatch API将其发送到CloudWatch。 (当然,该function必须有权写入CloudWatch。)

更多文档在这里: https : //docs.aws.amazon.com/AWSJavaScriptSDK/latest/AWS/CloudWatch.html