Skip to content

ILogger Show EntityFramework generated query, ignore other

DUONG Phu-Hiep edited this page Aug 11, 2020 · 3 revisions

This configuration logs all the SQL commands generated by EntifyFramework but disable all other logs.

public static readonly ILoggerFactory LoggerFactory = Microsoft.Extensions.Logging.LoggerFactory.Create(c =>
{
    c.ClearProviders()
        .AddNLog(LogQuickConfig.SetupFileAndConsole("./logs/sync-refund.log"))
        .SetMinimumLevel(LogLevel.Debug)
        .AddFilter("Microsoft.EntityFrameworkCore.Database.Command", LogLevel.Debug) //log SQL requests
        .AddFilter("Microsoft.EntityFrameworkCore.Model.Validation", LogLevel.Warning) //log bad database smell
        //disable other logs messages
        .AddFilter((category, logLevel) =>
        {
            if (category.StartsWith("Microsoft."))
                return logLevel > LogLevel.Error;
            else if (category.StartsWith("System."))
                return logLevel > LogLevel.Warning;
            else return true;
        })
    ;
});

in .csproj install package

<PackageReference Include="NLog.Extensions.Logging" Version="1.6.4" />
<PackageReference Include="ToolsPack.NLog" Version="2.0.0" />