如何在AKS中运行的Python Azure Function日志启用时间戳并合并行?
Azure Functions在Kubernetes Pod中日志优化:添加时间戳与合并单行输出
问题描述
当前在Kubernetes Pod中运行的Azure Functions日志输出分为两行,且缺少时间戳,示例如下:
info: Function.name_of_the_function.User[0] this is the info message from the function... info: Function.name_of_the_function.User[0] this is the info message from the function...
现有host.json配置:
"logging": { "applicationInsights": { "samplingSettings": { "isEnabled": false, "excludedTypes": "Request" } }, "console": { "isEnabled": "false", "DisableColors": true }, "fileLoggingMode": "always", "logLevel": { "Host": "Warning", "Function": "Warning", "Function.solr_catalog": "Warning", "Function.solr_catalog.User": "Information", "Azure.Core": "Warning", "Azure.Messaging": "Warning", "default": "none" } }
需要解决两个问题:
- 在日志中添加时间戳
- 将每条日志合并为单行输出
解决方案
修改host.json中的logging.console配置,启用控制台日志并自定义输出格式,具体配置如下:
"logging": { "applicationInsights": { "samplingSettings": { "isEnabled": false, "excludedTypes": "Request" } }, "console": { "isEnabled": "true", "DisableColors": true, "format": "[{Timestamp:yyyy-MM-dd HH:mm:ss.fff zzz}] {Level:u3} {SourceContext}: {Message:lj}{NewLine}{Exception}" }, "fileLoggingMode": "always", "logLevel": { "Host": "Warning", "Function": "Warning", "Function.solr_catalog": "Warning", "Function.solr_catalog.User": "Information", "Azure.Core": "Warning", "Azure.Messaging": "Warning", "default": "none" } }
配置说明
console.isEnabled: "true":启用控制台日志输出,Kubernetes会采集容器的标准输出,便于通过kubectl logs查看format字段:自定义日志格式,其中:{Timestamp:yyyy-MM-dd HH:mm:ss.fff zzz}:添加带时区的精确时间戳{Level:u3}:将日志级别缩写为3个大写字母(如INF/WARN/ERR){Message:lj}:将多行日志消息合并为单行输出
- 保留原有
logLevel和applicationInsights配置,不影响现有日志级别控制和遥测设置
修改后日志效果
调整后的日志会变成单行格式,包含时间戳:
[2024-05-20 14:30:45.123 +08:00] INF Function.name_of_the_function.User: this is the info message from the function...
注意事项
- 该配置适用于.NET运行时的Azure Functions(基于Serilog日志框架)
- 若使用Python/Node.js等其他运行时,需对应调整运行时的日志格式配置逻辑,核心思路一致:输出单行日志并包含时间戳
内容的提问来源于stack exchange,提问作者freedev
相关产品推荐
相关产品推荐

