如何配置 .NET Core 日志记录 json 文件以忽略某些事件?

How to configure .NET Core logging json file to ignore certain events?

我想忽略产品系统中的某些警告。我得到的等效代码是这样的:

optionsBuilder
    .ConfigureWarnings(x => x.Ignore(RelationalEventId.MultipleCollectionIncludeWarning));

是否可以在 appSettings.Production.json 中设置忽略?

目前是:

  "Logging": {
    "LogLevel": {
      "Default": "Trace",
      "Microsoft": "Warning",
      "Microsoft.Hosting.Lifetime": "Information",
      "Microsoft.EntityFrameworkCore": "Warning",
      "IdentityServer4": "Information"
    }
  },

我不是 EF Core 专家,但很明显这是两种不同类型的配置; builder 调用告诉 EF Core 要记录或不记录哪些事件,而 appsettings 只是指示日志框架在哪个级别监听哪些提供程序。您可能能够在给定的日志级别使整个提供程序静音,但这可能不够精细,无法仅过滤该提供程序中的特定 class 日志事件。

如果 EF Core 没有从配置对象中读取选项 class 的本机机制,并且您想要管理一组有限的开关(即只有一组事物可以一起打开或关闭),然后您可以编写自己的代码来帮助管理它。

配置class:

public class CustomEfCoreLoggingOptions 
{
    public const string Section = "CustomEfCoreLogging";
    public bool IgnoreMultipleCollectionIncludeWarning { get; set; }
}

应用设置:

"CustomEfCoreLogging" : {
  "IgnoreMultipleCollectionIncludeWarning" : true
}

在您的启动中:

var efLogging = Configuration.GetSection(CustomEfCoreLoggingOptions.Section).Get<CustomEfCoreLoggingOptions>();
var optionsBuilder = new DbContextOptionsBuilder();

if (efLogging.IgnoreMultipleCollectionIncludeWarning) optionsBuilder.ConfigureWarnings(x => x.Ignore(RelationalEventId.MultipleCollectionIncludeWarning));

//...