AWS Lambda Python 3.7 运行时异常记录

AWS Lambda Python 3.7 runtime exception logging

使用 Python 3.7 运行 时抛出的未处理异常似乎没有记录到 CloudWatch,因为它们在 Python 3.6 中。如何在 Python 3.7 中设置记录器来捕获此信息?

Also posted on AWS forum

要复制:

1.像这样创建一个 lambda 函数:

import logging
logger = logging.getLogger()
logger.setLevel(logging.DEBUG)
def lambda_handler(event, context):
logger.info("This shows fine")
raise Exception("I failed")  

2。 运行这个函数使用Python3.6运行时间

START RequestId: a2b6038b-0e5f-11e9-9226-9dfc35a22dcc Version: $LATEST
[INFO]  2019-01-02T07:25:52.797Z    a2b6038b-0e5f-11e9-9226-9dfc35a22dcc //This shows fine
 I failed: Exception
Traceback (most recent call last):
File "/var/task/lambda_function.py", line 9, in lambda_handler
        raise Exception("I failed")
Exception: I failed

END RequestId: a2b6038b-0e5f-11e9-9226-9dfc35a22dcc
REPORT RequestId: a2b6038b-0e5f-11e9-9226-9dfc35a22dcc  Duration: 1.12 ms   Billed Duration: 100 ms     Memory Size: 128 MB Max Memory Used: 21 MB

2。切换到 Python 3.7 运行 时间并再次 运行 ... 没有堆栈跟踪

    START RequestId: 3840aa8e-0e5d-11e9-bece-45a2022a53c6 Version: $LATEST
    [INFO]  2019-01-02T07:08:35.170Z    3840aa8e-0e5d-11e9-bece-45a2022a53c6    This shows fine

    END RequestId: 3840aa8e-0e5d-11e9-bece-45a2022a53c6
    REPORT RequestId: 3840aa8e-0e5d-11e9-bece-45a2022a53c6  Duration: 2.20 ms   Billed Duration: 100 ms     Memory Size: 128 MB Max Memory Used: 20 MB  

奇怪,因为 Exception 是内置函数,它应该适用于 3.6 和 3.7。

作为解决方法,我建议创建自定义异常。这是一个简单的例子。

test.py

class Error(Exception):
    pass

class CustomException(Error):
    pass

raise CustomException("I failed")

这是 运行.

时的结果
TK$ python3 test.py 

Traceback (most recent call last):
 File "test.py", line 7, in <module>
    raise CustomException("I failed")
__main__.CustomException: I failed

是的,我注意到了。 为了克服我使用装饰器。

def log_errors(func: Callable[[dict, dict], None]):
    def wrapper(*args, **kwargs):
        try:
            func(*args, **kwargs)
        except Exception as err:
            warning(traceback.format_exc())
            raise err

    return wrapper

用法:

@log_errors
def handler(event, context):
...

这是 AWS Lambda 中的错误。我在 12 月中旬注意到它并提出了一个问题;响应包括以下内容:"I would like to let you know that this has been identified as a genuine issue and the Lambda team is currently working towards resolving it. But, unfortunately I do not have an ETA on when this issue will be resolved."

我的解决方案是恢复到 python3.6 运行时,直到亚马逊修复它。