Skip to content

Instantly share code, notes, and snippets.

@bdnf
Created January 30, 2020 09:38
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save bdnf/a75c637a72d19f915f2dae369f9d8d3e to your computer and use it in GitHub Desktop.
Save bdnf/a75c637a72d19f915f2dae369f9d8d3e to your computer and use it in GitHub Desktop.
A starter code that enables AWS Lambda to send data to Cloud Watch
const AWS = require('aws-sdk')
const axios = require('axios')
// Name of a service, any string
const serviceName = process.env.SERVICE_NAME
// URL of a service to test
const url = process.env.URL
// CloudWatch client
const cloudwatch = new AWS.CloudWatch();
exports.handler = async (event) => {
let endTime
let requestWasSuccessful
const startTime = timeInMs()
try {
await axios.get(url)
requestWasSuccessful = true
} catch (e) {
requestWasSuccessful = false
} finally {
endTime = timeInMs()
}
const totalTime = endTime - startTime
await cloudwatch.putMetricData({
MetricData: [
{
MetricName: 'Success',
Dimensions: [
{
Name: 'ServiceName',
Value: serviceName
}
],
Unit: 'Count',
Value: requestWasSuccessful ? 1 : 0
}
],
Namespace: 'Example/ServelessCode'
}).promise()
await cloudwatch.putMetricData({
MetricData: [
{
MetricName: 'Latency',
Dimensions: [
{
Name: 'ServiceName',
Value: serviceName
}
],
Unit: 'Milliseconds',
Value: totalTime
}
],
Namespace: 'Example/ServelessCode'
}).promise()
}
function timeInMs() {
return new Date().getTime()
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment