Home > Software design >  How to configure .NET Core logging json file to ignore certain events?
How to configure .NET Core logging json file to ignore certain events?

Time:11-04

I would like to ignore certain warnings in prod system. The code equivalent I was given is this:

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

Is it possible to set the ignore in appSettings.Production.json instead?

Currently it is:

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

CodePudding user response:

I'm not an EF Core expert, but it seems evident these are two different types of configuration; the builder call is telling EF Core what events to log or not, and the appsettings is just instructing the logging framework which providers to listen to at which levels. You might be able to mute the entire provider at a given log level, but that would likely not be granular enough to filter just a certain class of log events within that provider.

If EF Core does not have a native mechanism for reading in an Options class from a Configuration object and you have a limited set of switches you'd want to manage (i.e. just a single group of things that may be turned on or off together), then you can write your own to help manage it.

Configuration class:

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

Appsettings:

"CustomEfCoreLogging" : {
  "IgnoreMultipleCollectionIncludeWarning" : true
}

In your startup:

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

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

//...
  • Related