简体   繁体   English

python 登录aws lambda

[英]python logging in aws lambda

Something just doesn't click internally for me with pythons logging despite reading the documentation.尽管阅读了文档,但对于 pythons 日志记录,我内部并没有点击。

I have this code我有这个代码

import logging
logging.basicConfig(level=logging.INFO,format='%(levelname)s::%(message)s')
LOG = logging.getLogger("__name__")
LOG.info("hey")

If I run it from bash I get this:如果我从 bash 运行它,我会得到这个:

INFO::hey

If I run it in an aws lambda the "hey" doesn't shows up at all in the logs.如果我在 aws lambda 中运行它,“嘿”根本不会出现在日志中。

I then did a test setting the level on the logger by adding this:然后我通过添加以下内容对记录器的级别进行了测试:

LOG.setLevel(logging.INFO)

Run from bash I get the same thing I got before (desired format), but run from the lambda this shows up in the logs:从 bash 运行我得到了与之前相同的东西(所需格式),但是从 lambda 运行这显示在日志中:

[INFO] 2022-02-14T23:30:43.39Z eb94600a-af45-4124-99b6-d9651d6a3cf6 hey

Okay... that is pretty odd.好吧……这很奇怪。 The format is not the same as from bash.格式与 bash 不同。

I thought I could rationalize the first example because the output on bash is actually going to stderr.我想我可以合理化第一个例子,因为 bash 上的 output 实际上是去 stderr。 And I then assumed the aws lamdba logs just don't grab that.然后我假设 aws lamdba 日志不会抓住它。 But the second example is also going to stderr on bash, yet it shows up in the lambda logs but with the wrong format.但第二个示例也将在 bash 上发送到 stderr,但它显示在 lambda 日志中,但格式错误。 So clearly I am missing something.很明显我错过了一些东西。

What is going on under the hood here?幕后发生了什么?

When your Lambda runs, a harness is running that does some basic bootstrap and then loads your module and invokes it.当您的 Lambda 运行时,一个 harness 正在运行,它会执行一些基本的引导程序,然后加载您的模块并调用它。 Part of that bootstrap in the AWS Lambda Python Runtime replaces the standard Python logger with its own: AWS Lambda Python 运行时中的部分引导程序用它自己的记录器替换了标准的 Python 记录器:

    logger_handler = LambdaLoggerHandler(log_sink)
    logger_handler.setFormatter(
        logging.Formatter(
            "[%(levelname)s]\t%(asctime)s.%(msecs)dZ\t%(aws_request_id)s\t%(message)s\n",
            "%Y-%m-%dT%H:%M:%S",
        )
    )
    logger_handler.addFilter(LambdaLoggerFilter())

This behavior is formally documented by AWS as AWS Lambda function logging in Python , under the section "Logging library".此行为由 AWS 正式记录为AWS Lambda function logging in Python ,在“Logging library”部分下。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM