将 python 日志记录与 AWS Lambda 结合使用 [英] Using python Logging with AWS Lambda

查看:33
本文介绍了将 python 日志记录与 AWS Lambda 结合使用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

正如 AWS 文档所建议的那样:

As the AWS documentation suggests:

import logging
logger = logging.getLogger()
logger.setLevel(logging.INFO)
def my_logging_handler(event, context):
    logger.info('got event{}'.format(event))
    logger.error('something went wrong')

现在我做了:

import logging
logging.basicConfig(level = logging.INFO)
logging.info("Hello World!")

第一段代码打印在 Cloud Watch 控制台中,但第二段没有.

The first snippet of code prints in the Cloud Watch console, but the second one no.

我没有看到任何区别,因为这两个片段都使用了根记录器.

I didn't see any difference as the two snippets are using the root logger.

推荐答案

日志似乎不起作用的原因是因为 AWS Lambda Python 运行时 预配置日志处理程序,根据所选的运行时版本,可能会修改所记录消息的格式,并且可能如果可用,还可以向记录添加一些元数据.预配置的是日志级别.这意味着无论您尝试发送何种类型的日志消息,它实际上都不会打印.

The reason that logging does not seem to work is because the AWS Lambda Python runtime pre-configures a logging handler that, depending on the version of the runtime selected, might modify the format of the message logged, and might also add some metadata to the record if available. What is not preconfigured though is the log-level. This means that no matter the type of log-message you try to send, it will not actually print.

作为 AWS 文档本身,要正确使用AWS Lambda 上下文中的 logging 库,您只需要为 root-logger 设置日志级别:

As AWS documents themselves, to correctly use the logging library in the AWS Lambda context, you only need to set the log-level for the root-logger:

import logging
logging.getLogger().setLevel(logging.INFO)

如果您希望 Python 脚本既可以在 AWS Lambda 上执行,又可以使用本地 Python 解释器,您可以检查是否配置了处理程序,然后回退到 basicConfig (否则会创建默认的 stderr 处理程序):

If you want your Python-script to be both executable on AWS Lambda, but also with your local Python interpreter, you can check whether a handler is configured or not, and fall back to basicConfig (which creates the default stderr-handler) otherwise:

if len(logging.getLogger().handlers) > 0:
    # The Lambda environment pre-configures a handler logging to stderr. If a handler is already configured,
    # `.basicConfig` does not execute. Thus we set the level directly.
    logging.getLogger().setLevel(logging.INFO)
else:
    logging.basicConfig(level=logging.INFO)

这篇关于将 python 日志记录与 AWS Lambda 结合使用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆