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?
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 :)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With