Ruan Bekker's Blog

From a Curious mind to Posts on Github

Snippet: Create Custom CloudWatch Metrics With Python

A quick post on how create custom CloudWatch Metrics using Python on AWS.

After you produced the metrics into CloudWatch, you will be able to see them when navigating to:

  • CloudWatch / Metrics / Custom Namespaces / statusdash/ec2client

When selecting:

1
2
Select Metric: SomeKey1, SomeKey2
Select MetricName HttpResponseTime

And should look like this:

The Script:

The python script that will be using boto3 to talk to AWS:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
import boto3
import random
cloudwatch = boto3.Session(region_name='eu-west-1').client('cloudwatch')
response = cloudwatch.put_metric_data(
MetricData = [
    {
        'MetricName': 'HttpResponseTime',
        'Dimensions': [
            {
                'Name': 'Server',
                'Value': 'app.example.com'
            },
            {
                'Name': 'Client',
                'Value': 'Client-ABC'
            },
        ],
        'Unit': 'Milliseconds',
        'Value': random.randint(20, 50)
    },
],
Namespace = 'statusdash/ec2client'
)
print response

Resources:

https://stackify.com/custom-metrics-aws-lambda/ https://www.syntouch.nl/custom-cloudwatch-metrics-in-python-yes-we-can/ <- psutil https://aws.amazon.com/blogs/devops/new-how-to-better-monitor-your-custom-application-metrics-using-amazon-cloudwatch-agent/ https://medium.com/@mrdoro/aws-lambda-as-the-website-monitoring-tool-184b09202ae2