在lambda中我用来定期检查服务我检查服务器的结果值,并希望将发布到AWS cloudwatch的值作为度量标准来形成线图。
我不能为我的生活想象我们如何做到这一点。 2个小时围绕AWS文档进行梳理无处可去。这甚至可能吗?
要明确这不是关于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();
};
答案 0 :(得分:14)
是的,这是可能的:
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 API将其发送到CloudWatch。 (当然,该函数必须具有写入CloudWatch的权限。)
此处有更多文档:https://docs.aws.amazon.com/AWSJavaScriptSDK/latest/AWS/CloudWatch.html
答案 1 :(得分:0)
如果要避免引入同步cloudwatch调用会带来的延迟影响,可以对正在发布的异步日志使用指标筛选器。
参考:https://docs.aws.amazon.com/AmazonCloudWatch/latest/logs/MonitoringLogData.html