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

如何在.NET Core的日志JSON配置文件中忽略指定事件?

可以实现,有两种常用方案,你可以根据自己的需求选择:

方案1:仅过滤日志输出(无需修改C#代码)

如果你只需要生产环境不打印这条警告,不需要修改EF Core的内部触发逻辑,直接修改appSettings.Production.json的Logging配置段即可,新增对应警告的日志级别配置为None:

"Logging": {
  "LogLevel": {
    "Default": "Trace",
    "Microsoft": "Warning",
    "Microsoft.Hosting.Lifetime": "Information",
    "Microsoft.EntityFrameworkCore": "Warning",
    // 新增这一行即可过滤对应警告的日志输出
    "Microsoft.EntityFrameworkCore.Query.MultipleCollectionIncludeWarning": "None",
    "IdentityServer4": "Information"
  }
},

方案2:完全禁用警告触发(和原硬编码效果完全一致)

如果你需要和原来ConfigureWarnings.Ignore完全一致的效果(EF Core内部完全不触发该警告,不会被任何自定义告警逻辑捕获),可以通过配置读取+动态应用规则的方式实现:

  1. 首先在appSettings.Production.json新增EF Core忽略警告的配置段:
"EFCore": {
  "IgnoredWarnings": [ "MultipleCollectionIncludeWarning" ]
}
  1. 调整DbContext的注册代码,读取配置动态应用忽略规则:
builder.Services.AddDbContext<你的DbContext类名>((serviceProvider, optionsBuilder) =>
{
    var config = serviceProvider.GetRequiredService<IConfiguration>();
    var ignoredWarningList = config.GetSection("EFCore:IgnoredWarnings").Get<string[]>() ?? Array.Empty<string>();

    optionsBuilder.UseSqlServer("你的数据库连接字符串")
        .ConfigureWarnings(warningConfig =>
        {
            foreach (var warningName in ignoredWarningList)
            {
                if (Enum.TryParse<RelationalEventId>(warningName, out var targetEventId))
                {
                    warningConfig.Ignore(targetEventId);
                }
            }
        });
});

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.27 15:54:03