Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to log Entity Framework Core operations by NLog

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?

like image 728
Mikhail Avatar asked Mar 05 '23 08:03

Mikhail


1 Answers

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

like image 129
Julian Avatar answered Mar 07 '23 23:03

Julian