【问题标题】:How to publish FROM an AWS lambda to a cloud watch metric in Node.js如何从 AWS lambda 发布到 Node.js 中的云观察指标
【发布时间】:2017-04-04 09:31:10
【问题描述】:

在我用来定期检查服务的 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();
};

【问题讨论】:

    标签: node.js amazon-web-services lambda


    【解决方案1】:

    是的,这是可能的:

    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

    【讨论】:

      【解决方案2】:

      如果您想避免引入同步 cloudwatch 调用所带来的延迟影响,您可以对正在发布的异步日志使用指标过滤器。

      参考:https://docs.aws.amazon.com/AmazonCloudWatch/latest/logs/MonitoringLogData.html

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2017-10-11
        • 1970-01-01
        • 1970-01-01
        • 2021-02-26
        • 1970-01-01
        • 2017-06-26
        • 1970-01-01
        • 2021-06-05
        相关资源
        最近更新 更多