Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Logging Generated SQL with EF Core 2 and Nlog

I'm getting a little confused with how to log the generated SQL with asp.net core 2 and EntityFrameworkCore 2 and the correct way to go about it.

After reading the this link from the MS docs it is saying that I should add during the services configuration in the startup.cs using .UseLoggerFactory(<LoggerFactory>).

However, this seems outdated as when I look to add the logger I get this message;

Visual Studio 2017 Message for UseLoggerFactory

Could someone please tell me the best way to add the logger to log the SQL for debug purposes?

I also plan to use Nlog going forward for all my logging as opposed to the built in logging facilities, I assume the approach (In that the Nlog loggerfactory is injected instead of the default MS instance) for this would be the same or are there any configuration differences (with regards to using NLog)?

like image 871
Matthew Flynn Avatar asked Apr 11 '18 05:04

Matthew Flynn


People also ask

Does NLog work with .NET Core?

NLog can be fully integrated with Microsoft Extensible Logging (and ASP.NET Core), without it needing to replace the standard Microsoft LoggerFactory. NLog automatically captures LogEvent properties and can use them in structured logging target output.

How do I log into SQL Entity Framework?

Or, just call the AddConsole() method on LoggerFactory to log SQL queries, by default. public static readonly ILoggerFactory consoleLoggerFactory = new LoggerFactory(). AddConsole(); Now, this will log the following query information which saving an entity using the DbContext .

Is EF core faster than EF6?

Entity Framework (EF) Core, Microsoft's object-to-database mapper library for . NET Framework, brings performance improvements for data updates in version 7, Microsoft claims. The performance of SaveChanges method in EF7 is up to 74% faster than in EF6, in some scenarios.


1 Answers

First register NLog as described on the official docs

Then inject an ILoggerFactory in your Startup class

private readonly ILoggerFactory _factory;
public Startup(IHostingEnvironment env, ILoggerFactory factory)
{ 
     _factory = factory ?? throw new ArgumentNullException(nameof(factory)); 
}

Finally link the factory as the logger factory to use for the DbContext

public void ConfigureServices(IServiceCollection services)
{
     services.AddDbContext<YourContext>(options => { options.UseLoggerFactory(_factory); });
}

EF Core statements are now logged using NLog enter image description here

like image 107
emp Avatar answered Nov 10 '22 03:11

emp