[英]Python lambda log format with multline output to cloudwatch
I can override the default Lambda python log format like so:我可以像这样覆盖默认的 Lambda python 日志格式:
LOG_FORMAT = '[%(levelname)s] %(asctime)s.%(msecs)dZ [%(filename)s] [%(funcName)s] %(message)s'
DATETIME_FORMAT = '%Y-%m-%dT%H:%M:%S'
logging.basicConfig(format=LOG_FORMAT, level=logging.INFO, datefmt=DATETIME_FORMAT, force=True)
LOG = logging.getLogger()
But I've noticed that the log lines will print onto separate lines in cloudwatch based on newline characters.但我注意到日志行将根据换行符打印到 cloudwatch 中的单独行上。
If I try and log a formatted XML document (to Cloudwatch) I end up, effectively, with new log lines for every line in the XML document.如果我尝试记录一个格式化的 XML 文档(到 Cloudwatch),我最终会有效地为 XML 文档中的每一行添加新的日志行。
But prior to modifying the default format the XML document would appear as a single log line, that I could easily copy & paste out of Cloudwatch但在修改默认格式之前,XML 文档将显示为单个日志行,我可以轻松地将其复制并粘贴到 Cloudwatch 之外
Prior to format change:格式更改之前:
[INFO] 2022-11-30T02:16:54.345Z dc2518d8-60f3-461c-812b-c70b1b836592
SNS message: <?xml version="1.0"?>
<Document>
...
</Document>
In cloudwatch clicking on the default output displays the entire document, where it can be easily copied.在 cloudwatch 中点击默认的 output 会显示整个文档,可以轻松复制到这里。
After format change:格式更改后:
[INFO] 2022-11-29T11:40:47.563Z [function.py] [handler] SNS message:
2022-11-29T11:40:47.563Z <?xml version="1.0"?>
2022-11-29T11:40:47.563Z <Document>
2022-11-29T11:40:47.563Z ...
2022-11-29T11:40:47.563Z</Document>
Is the default formatter parsing the string and replacing newline characters?默认格式化程序是否解析字符串并替换换行符? I know \r is treated differently to \n in CloudWatch.
我知道 \r 在 CloudWatch 中与 \n 的处理方式不同。
This is the Lamba Python runtime bootstrap code:这是 Lamba Python 运行时引导程序代码:
https://github.com/aws/aws-lambda-python-runtime-interface-client/blob/main/awslambdaric/bootstrap.py https://github.com/aws/aws-lambda-python-runtime-interface-client/blob/main/awslambdaric/bootstrap.py
Figured out a workaround by editing the existing formatter:通过编辑现有的格式化程序找出解决方法:
LOG = logging.getLogger()
LOG.setLevel(logging.INFO)
log_handler = LOG.handlers[0]
log_handler.setFormatter(logging.Formatter('[%(levelname)s] %(asctime)s.%(msecs)dZ [%(filename)s] [%(funcName)s] %(message)s\n'))
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.