Created
January 30, 2020 09:38
-
-
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
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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