How to log Entity Framework Core operations by NLog

8.4k Views Asked by At

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

There are 1 best solutions below

4
On

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 :)