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

切换Serilog后Azure日志流无法查看日志问题咨询

问题根源

Azure Functions 日志流默认仅捕获两类日志:

  1. 内置 ILogger 输出的、符合 host.json 中 logging 配置级别的日志
  2. 标准输出中符合 Azure 运行时预设格式的日志。你自定义的 Serilog Console 输出模板加了专属前缀,无法被运行时识别,同时 Serilog 注册逻辑没有正确对接 Azure Functions 的内置日志流管道,导致日志无法被日志流捕获。

修复步骤

1. 安装必要NuGet包

先安装 Serilog.Sinks.AzureFunctions,用于对接 Azure Functions 内置日志管道。

2. 调整Serilog注册代码

public static IServiceCollection AddLogging(this IServiceCollection services, IConfiguration configuration)
{
    // 优先使用Azure Functions内置注入的TelemetryConfiguration,避免配置不一致
    var telemetryConfig = TelemetryConfiguration.CreateDefault();
    telemetryConfig.InstrumentationKey = configuration.GetValue<string>("APPINSIGHTS_INSTRUMENTATIONKEY");
    
     Log.Logger = new LoggerConfiguration()
                     .ReadFrom.Configuration(configuration, "AzureFunctionsJobHost:Serilog")
                     .Destructure.ToMaximumCollectionCount(200)
                     .Destructure.ToMaximumDepth(8)
                     .WriteTo.ApplicationInsights(telemetryConfig, new TraceTelemetryConverter(), Serilog.Events.LogEventLevel.Information)
                     // 新增:写入Azure Functions内置日志管道,日志会自动同步到日志流
                     .WriteTo.AzureFunctionsLog()
                     .CreateLogger();
    services.AddLogging(lb =>
    {
        // 第二个参数改为false,不清除内置日志提供程序,保留原生日志流输出能力
        lb.AddSerilog(Log.Logger, false);
    });
    return services;
}

3. 调整host.json配置

移除 Serilog 下自定义格式的 Console Sink 配置,避免异常格式干扰日志捕获,同时保持内置日志级别和 Serilog 配置一致:

{
  "version": "2.0",
  "logging": {
    "console": {
      "isEnabled": true
    },
    "logLevel": {
      "default": "Debug",
      "Microsoft": "Warning",
      "System": "Warning",
      "Host": "Warning",
      "EIP": "Debug"
    },
    "applicationInsights": {
      "samplingSettings": {
        "isEnabled": true,
        "excludedTypes": "Request"
      }
    }
  },
  "Serilog": {
    "Using": [ "Serilog.Sinks.ApplicationInsights", "Serilog.Sinks.AzureFunctions" ],
    "MinimumLevel": { 
      "Default": "Debug",
      "Override": {
        "Microsoft": "Warning",
        "System": "Warning",
        "Host": "Warning",
        "EIP": "Debug"
      }
    },
    "Enrich": [ "FromLogContext" ]
  },
  "extensions": {
    "serviceBus": {
      "messageHandlerOptions": {
        "autoComplete": false
      }
    }
  },
  "functionTimeout": "00:05:00"
}

可选配置:保留Console输出

如果你需要保留 Serilog 的 Console Sink,将输出模板调整为 Azure 运行时可识别的无自定义前缀格式即可:

"WriteTo": [
  {
    "Name": "Console",
    "Args": {
      "outputTemplate": "[{Level:u3}] {Message}{NewLine}{Exception}"
    }
  }
]

内容的提问来源于stack exchange,提问作者venkatesh k

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.23 20:24:03