如何在Node.js中从AWS Lambda发布到云监视指标 [英] How to publish FROM an AWS lambda to a cloud watch metric in Node.js

查看:95
本文介绍了如何在Node.js中从AWS Lambda发布到云监视指标的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在用于定期检查服务的lambda内,我检查了来自服务器的结果的值,并且希望将该值作为度量标准发布到AWS cloudwatch,以形成折线图.

Inside a lambda I use to periodically check in on a service I check the value of the result from the server and I want that value published to AWS cloudwatch as a metric to form a linechart.

我无法为自己的生活弄清楚我们如何做到这一点. 2个小时围绕AWS文档进行梳理无济于事,这甚至可能吗?

I can't for the life of me figure our how this is done. 2 hours combing around the AWS docs leads nowhere.Is this even possible?

请注意,这不是关于lambda的指标,它是从lamdba发布的指标.

To be clear this isn't a metric ABOUT a lambda, it's a metric published FROM the 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
}
});

首先,创建要存储为指标的数据,然后使用CloudWatch API将其发送到CloudWatch. (当然,该功能必须具有写入CloudWatch的权限.)

First your create the data that you want to store as a metric, the you use the CloudWatch API to send it to CloudWatch. (Of course the function must have permission to write to CloudWatch.)

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

这篇关于如何在Node.js中从AWS Lambda发布到云监视指标的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆