使用 Amazon 开发工具包获取 CloudWatch 指标统计数据 - Amazon CloudWatch
Amazon Web Services 文档中描述的 Amazon Web Services 服务或功能可能因区域而异。要查看适用于中国区域的差异,请参阅中国的 Amazon Web Services 服务入门

使用 Amazon 开发工具包获取 CloudWatch 指标统计数据

以下代码示例展示如何获取 Amazon CloudWatch 指标统计数据。

Python
适用于 Python (Boto3) 的 SDK

class CloudWatchWrapper: """Encapsulates Amazon CloudWatch functions.""" def __init__(self, cloudwatch_resource): """ :param cloudwatch_resource: A Boto3 CloudWatch resource. """ self.cloudwatch_resource = cloudwatch_resource def get_metric_statistics(self, namespace, name, start, end, period, stat_types): """ Gets statistics for a metric within a specified time span. Metrics are grouped into the specified period. :param namespace: The namespace of the metric. :param name: The name of the metric. :param start: The UTC start time of the time span to retrieve. :param end: The UTC end time of the time span to retrieve. :param period: The period, in seconds, in which to group metrics. The period must match the granularity of the metric, which depends on the metric's age. For example, metrics that are older than three hours have a one-minute granularity, so the period must be at least 60 and must be a multiple of 60. :param stat_types: The type of statistics to retrieve, such as average value or maximum value. :return: The retrieved statistics for the metric. """ try: metric = self.cloudwatch_resource.Metric(namespace, name) stats = metric.get_statistics( StartTime=start, EndTime=end, Period=period, Statistics=stat_types) logger.info( "Got %s statistics for %s.", len(stats['Datapoints']), stats['Label']) except ClientError: logger.exception("Couldn't get statistics for %s.%s.", namespace, name) raise else: return stats
  • GitHub 中查找说明和更多代码。

  • 有关 API 详细信息,请参阅 Amazon 适用于 Python (Boto3) 的 SDK API 参考中的 GetMetricStatistics

有关 Amazon 开发工具包开发人员指南和代码示例的完整列表,包括帮助入门和有关早期版本的信息,请参阅 将 CloudWatch 与 Amazon 开发工具包结合使用