在我用来定期检查服务的lambda中,我检查来自服务器的结果的值,并希望将该值作为度量发布到AWS cloudwatch,以形成线形图。
我无论如何也搞不懂这是怎么做到的。2小时梳理亚马逊网络服务的文档导致了nowhere.Is,这是可能的吗?
需要说明的是,这不是关于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();
};
发布于 2016-11-21 21:47:22
是的,这是可能的:
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
}
});
首先创建要存储为度量的数据,然后使用CloudWatch应用编程接口将其发送到CloudWatch。(当然,该函数必须具有写入CloudWatch的权限。)
更多文档在这里:https://docs.aws.amazon.com/AWSJavaScriptSDK/latest/AWS/CloudWatch.html
发布于 2019-04-16 03:58:49
如果您希望避免引入sync cloudwatch调用所带来的延迟影响,您可以在正在发布的异步日志上使用Metric Filters。
参考:https://docs.aws.amazon.com/AmazonCloudWatch/latest/logs/MonitoringLogData.html
https://stackoverflow.com/questions/40712522
复制相似问题