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

Azure Function如何将ILogger替换为Serilog并解决日志重复及Log Stream问题

问题解决方法

1. 修复重复日志问题

你当前遇到的重复日志由两个原因导致:

  • 重复注册Serilog日志提供器:AddSerilog方法本身已经完成了SerilogLoggerProvider的注册,你后续手动AddSingleton又新增了一次,导致同一条日志被Serilog输出两次,对应你示例里前两条完全相同的INF日志
  • 未屏蔽默认提供器的Info级输出:Azure Functions运行时强制要求保留内置的文件日志提供器,直接调用ClearProviders就会触发你遇到的服务缺失报错,所以需要通过配置拉高默认提供器的输出等级,让它只输出Warning及以上的日志,就不会出现第三条默认格式的重复日志

启动类配置修改

调整你的启动代码,删除重复的注册项,补充系统命名空间的日志过滤规则:

var logger = new LoggerConfiguration()
    .MinimumLevel.Override("Microsoft", LogEventLevel.Warning)
    .MinimumLevel.Override("Microsoft.Azure.WebJobs", LogEventLevel.Warning)
    .MinimumLevel.Override("Worker", LogEventLevel.Warning)
    .MinimumLevel.Override("Host", LogEventLevel.Warning)
    .Enrich.FromLogContext()
    .WriteTo.Console()
    .WriteTo.ApplicationInsights(TelemetryConfiguration.Active, TelemetryConverter.Traces)
    // 新增写入Function默认日志目录的配置,用于适配Log Stream采集
    .WriteTo.File(
        path: @"D:\home\LogFiles\Application\Functions\serilog-.log",
        rollingInterval: RollingInterval.Day,
        retainedFileCountLimit: 7
    )
    .CreateLogger();
Log.Logger = logger;

builder.Services.AddLogging(options =>
{
    // 不要调用ClearProviders,会触发运行时服务校验错误
    options.AddSerilog(logger, dispose: true);
});
// 下方两行是重复注册代码,直接删除即可
// builder.Services.AddSingleton<ILoggerProvider>(new SerilogLoggerProvider(Log.Logger));
// builder.Services.AddSingleton(Log.Logger);

如果你使用的是Linux部署的Azure Functions,把File Sink的路径改成/home/LogFiles/Application/Functions/serilog-.log即可。

host.json配置修改

在项目根目录的host.json中添加日志等级配置,拉高默认提供器的输出阈值,禁用内置控制台输出:

{
  "version": "2.0",
  "logging": {
    "logLevel": {
      "default": "Warning",
      "Function": "Information",
      "Host.Aggregator": "Warning",
      "Host.Results": "Warning"
    },
    "console": {
      "isEnabled": false
    }
  }
}

2. 修复Azure Log Stream不显示Serilog日志的问题

上述配置中已经给Serilog添加了File Sink,写入的是Azure Function运行时默认的日志采集目录,Log Stream会自动扫描这个目录下的所有日志文件,配置完成后所有Serilog输出的日志就会正常展示在Log Stream中。

如果你的项目接入了Application Insights,也可以直接在Application Insights的日志查询界面查看全量的Serilog日志,数据和Log Stream完全同步。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.04 22:54:00