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

求助:Azure Functions(.NET Isolated环境)JSON格式日志配置失效

Azure Functions (.NET Isolated) 配置JSON格式日志解决方案

1. 安装必要NuGet包

首先确保项目引用了Microsoft.Extensions.Logging.Console包,JSON日志格式化器依赖此包。执行以下命令安装:

dotnet add package Microsoft.Extensions.Logging.Console

2. 配置Program.cs

在.NET Isolated模式下,日志核心配置需在Program.cs中通过ConfigureLogging指定,示例代码如下:

var host = new HostBuilder()
    .ConfigureFunctionsWorkerDefaults()
    .ConfigureLogging(logging =>
    {
        // 移除默认控制台日志提供器,避免冲突
        logging.ClearProviders();
        // 添加JSON格式控制台日志支持
        logging.AddConsole(options =>
        {
            options.FormatterName = "json";
        }).AddConsoleFormatter<JsonConsoleFormatter, JsonConsoleFormatterOptions>();
    })
    .Build();

host.Run();

若需自定义JSON输出格式(如调整时间戳、包含日志作用域),可扩展配置JsonConsoleFormatterOptions:

logging.AddConsole(options =>
{
    options.FormatterName = "json";
}).AddConsoleFormatter<JsonConsoleFormatter, JsonConsoleFormatterOptions>(options =>
{
    options.IncludeScopes = true;
    options.TimestampFormat = "yyyy-MM-dd HH:mm:ss.fff";
    options.UseUtcTimestamp = false;
});

3. 同步host.json配置

修改host.json,确保日志配置与Program.cs匹配,避免设置被覆盖:

{
  "version": "2.0",
  "logging": {
    "applicationInsights": {
      "samplingSettings": {
        "isEnabled": true,
        "excludedTypes": "Request"
      }
    },
    "console": {
      "formatterName": "json",
      "formatterOptions": {
        "includeScopes": true,
        "timestampFormat": "yyyy-MM-dd HH:mm:ss.fff"
      }
    },
    "logLevel": {
      "Default": "Information",
      "Microsoft": "Warning"
    }
  }
}

4. 排查要点

  • 确认项目为**.NET Isolated模式**,In-Process模式的日志配置逻辑完全不同。
  • 核对NuGet包版本,建议使用与当前.NET SDK版本兼容的Microsoft.Extensions.Logging.Console包。
  • 启动函数时查看控制台初始化日志,确认JSON格式化器是否加载成功,有无报错信息。
  • 本地调试优先使用func start命令启动,避免IDE调试环境的日志配置干扰。

内容的提问来源于stack exchange,提问作者Matt Phillips

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.23 19:32:19