【问题标题】:How to get cloudwatch metrics of a lambda using boto3 and lambda python?如何使用 boto3 和 lambda python 获取 lambda 的 cloudwatch 指标?
【发布时间】:2022-01-09 04:09:00
【问题描述】:

我有一个 Lambda,我试图从另一个 Lambda 的 Cloudwatch 获取指标(特别是调用次数)。我正在关注来自https://boto3.amazonaws.com/v1/documentation/api/latest/reference/services/cloudwatch.html#CloudWatch.Client.get_metric_data 的文档以及我在互联网上找到的其他一些示例,但我无法使其工作。当我运行代码时,响应显示为空值,所以我可能会错过一些东西。

例如,在下面的代码中,我试图从 11 月获取指标,当时我正在使用我希望分析的 Lambda(称为“lambda-function-to-analyze”)进行一些测试。

def get_metric_data():
    
    cloudwatch = boto3.client('cloudwatch')
    date = datetime.now()
    first = date.replace(day=1)
    last = date.replace(day = calendar.monthrange(date.year, date.month)[1])
    print('first: ', first)
    print('last: ', last)
    
    targetGroupARN='arn:aws:lambda:us-east-1:1234567890:function:lambda-function-to-analyze'
    tgarray=targetGroupARN.split(':')
    target=tgarray[-1]
    print(target)
    
    response = cloudwatch.get_metric_data(
        MetricDataQueries=[
            {
                'Id': 'myrequest',
                'MetricStat': {
                    'Metric': {
                        'Namespace': 'Invocations',
                        'MetricName': 'Number of invokes',
                        'Dimensions': [
                            {
                                'Name': 'lambda',
                                'Value': target
                            },
                        ]
                    },
                    'Period': 300,
                    'Stat': 'Sum',
                    # 'Unit': 'Count'
                }
            },
        ],
        # StartTime=datetime(first.year, first.month, first.day),
        StartTime=datetime(2021, 11, 1),
        # EndTime=datetime(last.year, last.month, last.day),
        EndTime=datetime(2021, 11, 30),
    )
    
    print(response)
    return response

【问题讨论】:

    标签: python amazon-web-services aws-lambda amazon-cloudwatch


    【解决方案1】:

    我认为主要问题是您的 MetricName 字段。也许尝试像这样更改您的NamespaceMetricName

    {
    "Namespace": "AWS/Lambda",
    "MetricName": "Invocations",
    ...
    }
    

    【讨论】:

    • 你好 D.Tate。感谢您很久以后的回复。我在发布的同一天解决了这个问题,但没有更新帖子。但这确实是你描述的问题。
    • @anubiros_theron 亲爱的,很高兴听到它
    猜你喜欢
    • 1970-01-01
    • 2023-01-03
    • 2017-04-15
    • 2017-07-30
    • 2019-12-02
    • 2020-04-03
    • 2017-08-04
    • 2019-07-16
    • 2019-06-26
    相关资源
    最近更新 更多