Put a set of data into a CloudWatch metric using an Amazon SDK - Amazon CloudWatch
Services or capabilities described in Amazon Web Services documentation might vary by Region. To see the differences applicable to the China Regions, see Getting Started with Amazon Web Services in China (PDF).

Put a set of data into a CloudWatch metric using an Amazon SDK

The following code example shows how to put a set of data into an Amazon CloudWatch metric.

Action examples are code excerpts from larger programs and must be run in context. You can see this action in context in the following code examples:

SDK for Python (Boto3)

There's more on GitHub. Find the complete example and learn how to set up and run in the Amazon Code Examples Repository.

class CloudWatchWrapper: """Encapsulates Amazon CloudWatch functions.""" def __init__(self, cloudwatch_resource): """ :param cloudwatch_resource: A Boto3 CloudWatch resource. """ self.cloudwatch_resource = cloudwatch_resource def put_metric_data_set(self, namespace, name, timestamp, unit, data_set): """ Sends a set of data to CloudWatch for a metric. All of the data in the set have the same timestamp and unit. :param namespace: The namespace of the metric. :param name: The name of the metric. :param timestamp: The UTC timestamp for the metric. :param unit: The unit of the metric. :param data_set: The set of data to send. This set is a dictionary that contains a list of values and a list of corresponding counts. The value and count lists must be the same length. """ try: metric = self.cloudwatch_resource.Metric(namespace, name) metric.put_data( Namespace=namespace, MetricData=[{ 'MetricName': name, 'Timestamp': timestamp, 'Values': data_set['values'], 'Counts': data_set['counts'], 'Unit': unit}]) logger.info("Put data set for metric %s.%s.", namespace, name) except ClientError: logger.exception("Couldn't put data set for metric %s.%s.", namespace, name) raise
  • For API details, see PutMetricData in Amazon SDK for Python (Boto3) API Reference.

For a complete list of Amazon SDK developer guides and code examples, see Using CloudWatch with an Amazon SDK. This topic also includes information about getting started and details about previous SDK versions.