I have a .net core 2.2 applications which is using a SQL database. I have written some unit tests using EF Core In Memory provider to test my data access code. I wanted to get the SQL logs generated(basically wanted to know the SQL statements getting generated. I referred this article https://learn.microsoft.com/en-us/archive/msdn-magazine/2018/october/data-points-logging-sql-and-change-tracking-events-in-ef-core, but it was not working(can not see any logs). Finally I ended up something like
public class TestFixture: IDisposable
{
private static readonly LoggerFactory _loggerFactory
= new LoggerFactory(new[] {
new DebugLoggerProvider((category, level) =>
level == LogLevel.Debug)
//new ConsoleLoggerProvider ((category, level) =>
// category == DbLoggerCategory.Database.Command.Name &&
// level == LogLevel.Debug, true)
});
#region Constructor(s)
public TestFixture()
{
}
#endregion
#region Public Method(s)
public MyDbContext CreateMyDbContext()
{
var options = new
DbContextOptionsBuilder<MyDbContext>().UseInMemoryDatabase(
"MyDb")
.UseLoggerFactory(_loggerFactory)
.EnableSensitiveDataLogging()
.UseQueryTrackingBehavior(QueryTrackingBehavior.NoTracking).Options;
return new MyDbContext(options);
}
#endregion
Now I am getting lot of logs in my VS output window which is not helpful. Looks like they are EF Core internal logs, but able to identify the SQL statements generated. Does anyone have any idea, how to get EF Core logs in a unit/integration test scenario when using EF Core In Memory provider?
I've just got this working. Just having both my
DbContextderived type andILoggerFactoryin the same DI container was not sufficient. But explicitly having my context type depend onILoggerFactoryand then passing this toUseLoggerFactoryin override ofOnConfiguringdid work.This is .NET 6 and EF Core 6.
I suspect if I was using
GenericHostthings might be different (who knows exactly what is setup in its container), but when building a minimal system to understand use of the In Memory Provider I want to avoid that).