How to log Entity Framework Core operations by NLog

.net-core entity-framework-core entity-framework-core-2.1 nlog

Question

I would like to use NLog to log SQL queries from Entity Framework Core in a manner similar to WebApi Core. How can I set it up?

1
2
5/7/2019 6:20:47 PM

Popular Answer

For logging with Entity Framework Core there are some docs here.

You need this: (see the docs)

public static readonly LoggerFactory MyLoggerFactory
    = new LoggerFactory(new[] {new ConsoleLoggerProvider((_, __) => true, true)});

and use the NLogLoggerProvider instead of the ConsoleLoggerProvider, from this package: https://www.nuget.org/packages/NLog.Extensions.Logging

and something like this:

protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
    => optionsBuilder
        .UseLoggerFactory(MyLoggerFactory) // Warning: Do not create a new ILoggerFactory instance each time
        .UseSqlServer(
            @"Server=(localdb)\mssqllocaldb;Database=EFLogging;Trusted_Connection=True;ConnectRetryCount=0");

also you need to load your NLog config file:

NLog.LogManager.LoadConfiguration("nlog.config");

Of course you need a nlog configuration (nlog.config or could be in C#), check https://github.com/NLog/NLog/wiki/Configuration-file for that.

Update: works well according the comments :)

5
5/8/2019 6:39:50 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