首页 > 解决方案 > 避免轮询和长时间运行的 lambda 任务

问题描述

我有一个 cloudwatch 组来监控我的应用程序启动的次数。然后我写了一个 Lamba 函数,它应该每 24 小时在 python 中使用 boto3 检索这些日志。为此,我启动一个查询,然后轮询 get_query_results 方法以查看它是否已完成。但是,这给我留下了一个使用大量资源的非常糟糕的实现。

有没有更好的方法来使用某种回调来做到这一点?

这是我正在使用的两个函数 https://boto3.amazonaws.com/v1/documentation/api/latest/reference/services/logs.html#CloudWatchLogs.Client.start_query

https://boto3.amazonaws.com/v1/documentation/api/latest/reference/services/logs.html#CloudWatchLogs.Client.get_query_results

query_id = cloudwatch_connector.start_query('fields @timestamp, @message|filter @message like /APPSTART/').get('queryId')

# Wait until it is completed
running = True
while running:
    response = cloudwatch_connector.get_query_results(query_id)
    status = response.get('status')
    if status == 'Complete':
        print("Done gathering logs")
        print(response)
        running = False
    if status == 'Failed' or status == 'Cancelled':
        raise Exception('Request either failed or was cancelled')
    time.sleep(1000)

我真正想做的是每晚 00:00 运行 Insights 查询并将其保存到文本文件中

标签: aws-lambda

解决方案


推荐阅读