Create custom metric
CloudWatch metric provides several metrics for Lambda functions such as the number of times the function is executed, the execution time of each time, error rates, and throttle count. To see the metrics of a certain function we do the following:
- Open the Lambda function’s dashboard
- Click the function book-list
- Click the Monitor tab, select Metrics
- Next we will create a new metric that sums up the number of hits to DynamoDB that fail
- Click the Code tab, add the following line of code at the top of the function
client_cloudwatch = boto3.client('cloudwatch')
- Add the following code to the except block of scan DynamoDB table before returning results
client_cloudwatch.put_metric_data(
Namespace='BooksList_Lambda',
MetricData=[
{
'MetricName': 'FailedConnectToDynamoDB',
'Dimensions': [
{
'Name': 'env',
'Value': 'staging'
},
],
'Value': 1.0,
'Unit': 'Seconds'
},
]
)
- The code helps you to create a new metric and push the data into it every time the connection to DynamoDB fails
- Give the function permission to access and push data into metric
- Click Configure tab, then select Permissions in the left menu. Click to lambda function’s role
- Expand the BooklistRole.. policy, then click Edit
- Click JSON tab, add below script to editor:
{
"Sid": "VisualEditor0",
"Effect": "Allow",
"Action": "cloudwatch:PutMetricData",
"Resourse": "*"
},
- Click Review policy, then click Save change
- Call GET API again
- Open the CloudWatch dashboard
- Click on Metrics in the left menu, then click All metrics
- In the Custom namespaces section appears the metric you created - BooksList_Lambda. Click it
- Press env
- Select staging, data display chart
- You can choose to display parameters according to 1 day or 1 week time, line or number displayed at the top of the graph
So we have created a custom metric. Next step we will use it to create a CloudWatch Alarm