123

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)

2
  • I know this is old, but where did you get Configuration from in your code? Commented Oct 30, 2021 at 18:33
  • 4
    Many of those EF Core log statements should have be coded/leveled at debug, and not info. Commented Aug 4, 2022 at 1:34

11 Answers 11

125

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"
    }
  }
Sign up to request clarification or add additional context in comments.

6 Comments

For disabling SQL command trace this is by far the best and simplest answer.
worked immediately, stopped seeing all the EF log for each select statement
logging.AddFilter was not working for me in the Blazor server project, but this approach worked
Only the last line is required right? What is the point of setting the other namespaces too?
@Wolfware, just for understanding where this line is located
|
89

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" ]
  }

4 Comments

Is there possibility to specify this MinimumLevel.Override("Microsoft.EntityFrameworkCore.Database.Command" thing in appsettings file?
Hi @AkmalSalikhov, please check my edited answer. Regards.
"Microsoft.EntityFrameworkCore.Model": "Warning" Did it for me. You can see in the logs what you need to override.
This should not be needed. You already set the Microsoft prefix to warning. That should include Microsoft.EntityFrameworkCore.Database.Command.
78

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();

3 Comments

If you want to disable all logging from certain categories, just set the LogLevel to LogLevel.Critical + 1 instead of just LogLevel.Warning
If you use LogLevel.None its value is 6, so no logging.
still works in .NET 8
19

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.

1 Comment

That's for the Microsoft Default Logger, not Serilog.
10

The answers doesn't work for me then i found this one:

On your Programs.cs, creating builder, add that line:

builder.Logging.AddFilter("Microsoft.EntityFrameworkCore.Database.Command", LogLevel.Warning);

Comments

8

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.

4 Comments

I've managed to exclude the context/source completely: .Filter.ByExcluding(Matching.FromSource("Microsoft.EntityFrameworkCore.Storage.IRelationalCommandBuilderFactory")) but don't know how to set minimum level
If you're doing your configuration from code, you should be able to do something like new LoggerConfiguration().MinimumLevel.Information().MinimumLevel.Override("Microsoft.EntityFrameworkCore.Storage.IRelationalCommandBuilderFactory", LogEventLevel.Warning)? I usually configure this from Serilog.Settings.Configuration JSON: {"Serilog": {"MinimumLevel": {"Default": "Information", "Override": {"Microsoft.EntityFrameworkCore.Storage.IRelationalCommandBuilderFactory": "Warning"}}}}
Those details added much practical value to the answer. I've tried it from code and it works. Thanks! I will try JSON config later and for sure it is preferred way as you have external control on logging options.
One very strange thing is that copy-pasted code didn't worked till I've found that there are some invisible characters in the string literal (I had to type it by hand to work; I think it is stack overflow issue?).
5

I had this issue in one of my projects and noticed that there's a bit more to look at in addition to earlier answers to this question.

You can do things like this:

    "Logging": {
        "IncludeScopes": true,
        "LogLevel": {
            "Default": "Debug",
            "System": "Information",
            "Microsoft": "Information",
            "Microsoft.EntityFrameworkCore": "Warning" <-- Note that this applies to EF Core, including everything in it.
        }
    }

What's also important is the order where things are added to the ILoggingBuilder.

    // This still will log EF messages to the console.
    serviceCollection.AddLogging(builder =>
        builder
            .AddConsole()
            .AddConfiguration(config.GetSection("Logging")));

    // This will apply the configuration to the console logger.
    serviceCollection.AddLogging(builder =>
        builder
            .AddConfiguration(config.GetSection("Logging"))
            .AddConsole());

Comments

3

Another way this can be configured differently is to add the following when registering the DbContext, so the CommandExecuted event is logged with a different LogLevel.

AddDbContext<DataStoreContext>(options =>
            options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection")))
            options.ConfigureWarnings(b => b.Log((RelationalEventId.CommandExecuted, LogLevel.Trace)));

1 Comment

BRUH thank you. Nothing above worked but this did. 🙏🏻
0

First find your source context where sql queries are being generated from. To do that, set outputTemplate as described here.

Then add it in LoggerConfiguration

.MinimumLevel.Override(<your_source_context>, LogEventLevel.Warning)

Comments

0

1.First I have installed these two Nuget packages.

enter image description here

2.Configurations goes like this

var logger = new LoggerConfiguration()
            .MinimumLevel.Information()
            .MinimumLevel.Override("Microsoft", LogEventLevel.Information)
            .MinimumLevel.Override("Microsoft.AspNetCore", LogEventLevel.Warning)
            .MinimumLevel.Override("Microsoft.EntityFrameworkCore.Database.Command", LogEventLevel.Warning)    
            .WriteTo.File(builder.Environment.WebRootPath + "/Logs/SUPCOMS-LOG-.log", rollingInterval: RollingInterval.Day)
            .CreateLogger();
        
builder.Logging.ClearProviders();
builder.Logging.AddSerilog(logger);

3.Log writing looks like this

public class MyClass: IMyInterface
{
    private readonly SupcomsDBContext _dBContext;
    private readonly ILogger<MyClass> _logger;

    public MyClass(SupcomsDBContext dBContext, ILogger<MyClass> logger)
    {
        this._dBContext = dBContext;
        this._logger = logger;
    }

    public bool MyMethod()
    { 
      _logger.LogError("I have an error");
      _logger.LogInformation("This is an information"  );
    }
}

4.Log file looks like this

enter image description here

1 Comment

How is it working? Is it this line builder.Logging.ClearProviders(); ?
0

this is a solution:

 <!--Skip non-critical Microsoft logs and so log only own logs-->
    <logger name="Microsoft.*" maxlevel="Fatal" final="true" /> 
    <!-- BlackHole without writeTo -->
    <logger name="*" minlevel="Trace" writeTo="mydatabase" />

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.