You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在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"
  }
}

需要解决两个问题:

  1. 在日志中添加时间戳
  2. 将每条日志合并为单行输出

解决方案

修改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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.16 03:11:13