Turn off .NET Core EF LoggerFactory at runtime

.net-core .net-core-logging c# ef-core-3.1 entity-framework-core

Question

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
0
3/23/2020 8:52:21 PM

Accepted 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.

0
3/23/2020 8:51:38 PM


Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow