How to prevent logging all of my Entity Framework SQL queries?

341 Views Asked by At

I'm using Serilog.Sinks.File and all of my SQL queries are getting logged.

Here is my configuration code:

// Configure Serilog
Log.Logger = new LoggerConfiguration()
    .ReadFrom.Configuration(context.Configuration)
    .WriteTo.File(Path.Combine(applicationContext.GetWorkingPath(), "TrackTrace.WorkerServices.log"),
        rollOnFileSizeLimit: true)
    .CreateLogger();

And here is my appsettings.json.

"Logging": {
  "LogLevel": {
    "Default": "Information",
    "Hangfire": "Information",
    "Microsoft": "Warning",
    "Microsoft.Hosting.Lifetime": "Information"
}

With the default Microsoft prefix set to Warning, I was expecting that to eliminate all of the SQL queries. What am I missing?

Update

Here's how I'm configuring my database.

// Configure database
services.AddDbContext<TrackTraceDbContext>(options =>
{
    options.UseSqlServer(
        connectionString,
        builder => builder.MigrationsAssembly(nameof(TTRailtraxEntities)));
});
1

There are 1 best solutions below

3
Guru Stron On BEST ANSWER

AFAIK Serilog does not use the default configuration section, try moving the setup to Serilog -> MinimumLevel -> Override:

  "Serilog": {
    "MinimumLevel": {
        "Default": "Information",
        "Override": {
            "Microsoft.EntityFrameworkCore": "Warning"
        }
    },

See the MinimumLevel, LevelSwitches, overrides and dynamic reload of the docs.

Alternatively you can ignore/change log levels on the context itself on per-event type basis (like here):

builder.Services.AddDbContext<TrackTraceDbContext>(b => b.UseSqlServer(...)
    .ConfigureWarnings(w => w.Ignore(RelationalEventId.CommandExecuted)));

Or override the logger factory:

builder.Services.AddDbContext<TrackTraceDbContext>(b => b.UseSqlServer(...)
    .UseLoggerFactory(new NullLoggerFactory()));