Turn off .NET Core EF LoggerFactory at runtime

2k views Asked by At

I am using a LoggerFactory for logging my EF Core (3.1.2) DataContext:

public static readonly ILoggerFactory LoggerFactory = Microsoft.Extensions.Logging.LoggerFactory.Create(builder => { builder.AddConsole().AddDebug(); });

protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{
    if (optionsBuilder.IsConfigured == false)
    {
        optionsBuilder.UseLoggerFactory(LoggerFactory);
        // ...
    }
}

How do I need to modify my code to deactivate or modify the LogLevel the logging during runtime? Is this even possible?

EDIT

The actual reason why I want to do this is very weird. My huge amount of EF Core Queries all finished (double checked with database) and still the expensive query log appear for like 10 minutes (no joke...) without pause in the developer console. During this time period, the whole application does not respond. I would like to turn off the logging for this huge batch of queries, but I don't want to turn it off completetly.

1

There are 1 answers

0
ˈvɔlə On BEST ANSWER

A workmate figured out a neat solution which fits very good to my scenario. Since I don't use any dependency injection to simplify my ability to run parallelized queries, I can turn off logging for specific DataContext instances using an optional constructor parameter:

public MyDataContext(bool enableLog = true)
{
    this.enableLog = enableLog;
}

protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{
    if (optionsBuilder.IsConfigured == false)
    {
        if (this.enableLog == true)
        {
            optionsBuilder.UseLoggerFactory(LoggerFactory);
            // ...
        }
    }
}

Now, I don't have to wait for my application to populate the (single-threaded) console debug output with millions of queries-logs anymore.