Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
485 views
in Technique[技术] by (71.8m points)

c# - 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)?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...