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

Azure Functions配置Serilog后Microsoft/System日志级别覆盖不生效问题求解

问题根因

核心原因有两个:

  1. Azure Functions运行时默认优先读取host.json中的日志配置,优先级高于Serilog代码中的最小级别覆盖规则,主机自身产生的Microsoft/System命名空间日志会直接按照host.json的默认配置输出,绕过Serilog的过滤规则
  2. 仅添加了Serilog日志提供程序,没有移除Azure Functions默认的内置日志提供程序,导致日志被双重处理,Serilog的过滤规则没有作用在全量日志流上

解决步骤

步骤1:修改host.json配置

在项目根目录的host.json文件中添加以下配置,先在主机侧将Microsoft/System日志默认级别调整为Warning,同时放开应用日志的级别限制:

{
  "version": "2.0",
  "logging": {
    "logLevel": {
      "default": "Information",
      "Microsoft": "Warning",
      "System": "Warning",
      "Function": "Information"
    }
  }
}

步骤2:修改Startup.cs代码,清空默认日志提供程序

调用ClearProviders()移除所有内置的默认日志提供程序,仅保留Serilog作为唯一日志输出源:

using System;
using Microsoft.Azure.Functions.Extensions.DependencyInjection;
using Microsoft.Extensions.DependencyInjection;
using Serilog;
using Serilog.Events;

[assembly: FunctionsStartup(typeof(SillyApp.Startup))]

namespace SillyApp
{
    public class Startup : FunctionsStartup
    {
        public override void Configure(IFunctionsHostBuilder builder)
        {
            var logger = new LoggerConfiguration()
                .MinimumLevel.Information()
                .MinimumLevel.Override("Microsoft", LogEventLevel.Warning)
                .MinimumLevel.Override("System", LogEventLevel.Warning)
                .WriteTo.Seq("https://blahblah.bla")
                .CreateLogger();

            builder.Services.AddLogging(b => {
                b.ClearProviders(); // 关键逻辑:清空所有默认日志提供程序
                b.AddSerilog(logger, dispose: true);
            });
        }
    }
}

步骤3:可选补充过滤规则

如果调整后还是收到多余的低级别Microsoft/System日志,可以在Serilog配置中增加显式过滤规则,直接拦截不符合要求的日志:

var logger = new LoggerConfiguration()
    .MinimumLevel.Information()
    .MinimumLevel.Override("Microsoft", LogEventLevel.Warning)
    .MinimumLevel.Override("System", LogEventLevel.Warning)
    // 新增显式过滤规则
    .Filter.ByExcluding(evt => 
        evt.Level < LogEventLevel.Warning && 
        (evt.Properties.TryGetValue("SourceContext", out var sourceCtx) && 
        (sourceCtx.ToString().StartsWith("\"Microsoft.") || sourceCtx.ToString().StartsWith("\"System.")))
    )
    .WriteTo.Seq("https://blahblah.bla")
    .CreateLogger();

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.26 01:54:04