You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

遍历Lambda函数获取最后执行时间时遇filter_log_events属性错误

解决Lambda客户端调用filter_log_events报错的问题

错误原因

filter_log_events是CloudWatch Logs服务的API方法,不是Lambda服务的。你用boto3.client('lambda')创建的Lambda客户端根本没有这个方法,所以才会报'Lambda' object has no attribute 'filter_log_events'的错误。

修正后的代码

import boto3
from botocore.exceptions import ClientError

def get_last_run_time(function_name):
    # 替换成CloudWatch Logs客户端
    logs_client = boto3.client('logs')
    log_group = f"/aws/lambda/{function_name}"

    try:
        log_response = logs_client.filter_log_events(
            logGroupName=log_group,
            orderBy='timestamp',
            descending=True,
            limit=1
        )
        if log_response['events']:
            last_invocation_time = log_response['events'][0]['timestamp']
            # 可选:把毫秒级时间戳转成可读格式
            # from datetime import datetime
            # last_invocation_time = datetime.fromtimestamp(last_invocation_time / 1000)
        else:
            last_invocation_time = "No recent invocations"
        # 修正原代码的变量名笔误:last_modified → last_invocation_time
        return last_invocation_time
    except ClientError as e:
        if e.response['Error']['Code'] == 'ResourceNotFoundException':
            return "Log group not found (function may never have run)"
        print(f"Error getting last run time for {function_name}: {e}")
        return str(e)
    except Exception as e:
        print(f"Unexpected error for {function_name}: {e}")
        return str(e)

额外注意事项

  • 确保执行代码的IAM角色拥有logs:FilterLogEvents权限,否则会出现权限不足的错误。
  • 如果Lambda函数从未执行过,对应的日志组不会自动创建,此时会触发ResourceNotFoundException,上面的代码已经处理了这种场景。

内容的提问来源于stack exchange,提问作者user3404930

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.18 05:34:50