Suppress SQL Queries logging in Entity Framework core

Entity Framework.Net Core

Entity Framework Problem Overview


I have a console .net core app that uses entity framework core. The app uses logging framework to write to file and console:

 serviceProvider = new ServiceCollection()
        .AddLogging()
        .AddDbContext<DataStoreContext>(options =>
            options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection")))
        .BuildServiceProvider();

    //configure console logging
    serviceProvider.GetService<ILoggerFactory>()
        .AddConsole(LogLevel.Debug)
        .AddSerilog();

    Log.Logger = new LoggerConfiguration()
        .MinimumLevel.Information()
        .WriteTo.RollingFile(Path.Combine(Directory.GetCurrentDirectory(), "logs/vcibot-{Date}.txt"))
        .WriteTo.RollingFile(Path.Combine(Directory.GetCurrentDirectory(), "logs/vcibot-errors-{Date}.txt"), LogEventLevel.Error)
        .CreateLogger();

    logger = serviceProvider.GetService<ILoggerFactory>()
        .CreateLogger<Program>();

Min Level for file output is set to Information. But with this setup output also contains SQL queries, here is the example:

> 2017-02-06 10:31:38.282 -08:00 [Information] Executed DbCommand (0ms) > [Parameters=[], CommandType='Text', CommandTimeout='30'] SELECT > [f].[BuildIdentifier], [f].[Branch], [f].[BuildDate], > [f].[StaticAssetSizeInKb] FROM [FileSizesHistoryEntries] AS [f]

Is there a way to disable the SQL queries logging (log them only in Debug log level)

Entity Framework Solutions


Solution 1 - Entity Framework

If you're using built-in logger, you can add filter to you ILoggingBuilder in Program.cs.

So, it can look like:

WebHost.CreateDefaultBuilder(args)
    // ...
    .ConfigureLogging((context, logging) => {
        var env = context.HostingEnvironment;
        var config = context.Configuration.GetSection("Logging");
        // ...
        logging.AddConfiguration(config);
		logging.AddConsole();
        // ...
        logging.AddFilter("Microsoft.EntityFrameworkCore.Database.Command", LogLevel.Warning);
	})
    // ...
    .UseStartup<Startup>()
    .Build();

Solution 2 - Entity Framework

Don't know if this is still an active question, but this is my solution, override the minimum level for "Microsoft.EntityFrameworkCore.Database.Command"

 Log.Logger = new LoggerConfiguration()
            .MinimumLevel.ControlledBy(loggingLevelSwitch)
            .MinimumLevel.Override("Microsoft.EntityFrameworkCore.Database.Command", Serilog.Events.LogEventLevel.Warning)
            .Enrich.WithProperty("app", environment.ApplicationName)
            .Enrich.FromLogContext()
            .WriteTo.RollingFile($"./Logs/{environment.ApplicationName}")
            .CreateLogger();

you can also have this on the appconfig.json

"Serilog": {
    "Using": [ "Serilog.Sinks.Console" ],
    "MinimumLevel": {
      "Default": "Verbose",
      "Override": {
        "Microsoft": "Warning",
        "Microsoft.EntityFrameworkCore.Database.Command": "Warning"
      }
    },
    "WriteTo": [
      {
        "Name": "Console",
        "Args": {
          "outputTemplate": "[{Timestamp:u}] [{Level:u3}] {SourceContext} {Message:lj}{NewLine}{Exception}"
        }
      },
    ],
    "Enrich": [ "FromLogContext", "WithExceptionDetails" ]
  }

Solution 3 - Entity Framework

If you are using the default Logger, in the appsettings.json (or appesttings.Development.json for dev startup) file:

"Logging": {
    "LogLevel": {
      "Default": "Debug",
      "System": "Information",
      "Microsoft": "Warning"        <----
    }
},

Set it to Warning instead of Information.

Solution 4 - Entity Framework

You want to change your Serilog configuration to set the minimum level for the Microsoft.EntityFrameworkCore.Storage.IRelationalCommandBuilderFactory context to Warning or higher.

You can find the context you need to change by setting the output template to something like [{Timestamp:HH:mm:ss} {SourceContext} [{Level}] {Message}{NewLine}{Exception}. Once you know the context you can set the template back to how it was before.

Solution 5 - Entity Framework

Found that if Logging section is modified in following manner i am not see EF logs message related to SQL queries:

  "Logging": {
    "LogLevel": {
      "Default": "Information",
      "Microsoft": "Information",
      "Microsoft.Hosting.Lifetime": "Information",
      "Microsoft.EntityFrameworkCore.Database.Command": "Warning"
    }
  }

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionvmgView Question on Stackoverflow
Solution 1 - Entity FrameworklambiduView Answer on Stackoverflow
Solution 2 - Entity FrameworkSantiago RobledoView Answer on Stackoverflow
Solution 3 - Entity FrameworkMordechaiView Answer on Stackoverflow
Solution 4 - Entity FrameworkmdonougheView Answer on Stackoverflow
Solution 5 - Entity FrameworkMichael UshakovView Answer on Stackoverflow