Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to publish FROM an AWS lambda to a cloud watch metric in Node.js

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.

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?

To be clear this isn't a metric ABOUT a lambda, it's a metric published FROM the lamdba.

Code:

'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();
};
like image 527
Christian Bongiorno Avatar asked Nov 21 '16 03:11

Christian Bongiorno


People also ask

How do I send Lambda output to CloudWatch?

Using the Lambda console Open the Functions page of the Lambda console. Choose a function. Choose Monitor. Choose View logs in CloudWatch.

Is it possible to publish your own metrics to CloudWatch?

You can publish your own metrics to CloudWatch using the AWS CLI or an API. You can view statistical graphs of your published metrics with the AWS Management Console. CloudWatch stores data about a metric as a series of data points. Each data point has an associated time stamp.


2 Answers

if you want to avoid the latency impact that introducing a sync cloudwatch call would introduce, you could use Metric Filters on the asynchronous logs that are being published.

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

like image 163
Umang Jain Avatar answered Oct 12 '22 23:10

Umang Jain


Yes, that is possible:

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
}
});

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.)

More documentation is here: https://docs.aws.amazon.com/AWSJavaScriptSDK/latest/AWS/CloudWatch.html

like image 39
Digitalkapitaen Avatar answered Oct 12 '22 23:10

Digitalkapitaen