I recently needed to send some custom metrics to AWS Cloudwatch. This is no rocket science but a lightweight example may safe some time implementing it. A very nice concept is to have so called dimensions for your metrics. You can think of them as metadata for your metrics you can filter and search for. All you need for this is Python, python-boto and a instance profile allowing you to write to cloudwatch.

from boto.ec2 import cloudwatch
from boto.utils import get_instance_metadata
import datetime


class CloudwatchMetricWriter(object):

    CW_NAMESPACE = "MyWebApp"

    def __init__(self, region="eu-west-1"):
        self.connection = cloudwatch.connect_to_region(region)

    def _get_instance_metadata(self):
        metadata = get_instance_metadata()
        return metadata['instance-id'], metadata['instance-type']

    def send_metrics(self, instance_id, instance_type, metrics, unit):
        self.connection.put_metric_data(self.CW_NAMESPACE, metrics.keys(),
                                        metrics.values(), unit=unit,
                                        dimensions={"InstanceType": instance_type, "InstanceId": instance_id})

    def example_send_metric(self):
        metadata = self._get_instance_metadata()
        metrics = {'AverageGetRequestDuration': 1.2,
                   'AveragePostRequestDuration': 2.2}
        self.send_metrics(metadata[0], metadata[1], metrics, "Milliseconds")


if __name__ == '__main__':
    cw = CloudwatchMetricWriter()
    print cw.example_send_metric()

 

Schreibe einen Kommentar

Deine E-Mail-Adresse wird nicht veröffentlicht. Erforderliche Felder sind mit * markiert.

*

Diese Website verwendet Akismet, um Spam zu reduzieren. Erfahre mehr darüber, wie deine Kommentardaten verarbeitet werden .