'Unable to get EF Core logs during unit tests when using EF Core In Memory provider
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://docs.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?
Solution 1:[1]
I've just got this working. Just having both my DbContext
derived type and ILoggerFactory
in the same DI container was not sufficient. But explicitly having my context type depend on ILoggerFactory
and then passing this to UseLoggerFactory
in override of OnConfiguring
did work.
This is .NET 6 and EF Core 6.
public class InMemoryBasicModelContext : BasicModelContext {
private readonly ILoggerFactory lf;
public InMemoryBasicModelContext(ILoggerFactory lf)
=> this.lf = lf;
protected override void OnConfiguring(DbContextOptionsBuilder builder)
=> builder.UseInMemoryDatabase("TestInMemory")
.ConfigureWarnings(b => b.Ignore(InMemoryEventId.TransactionIgnoredWarning))
.EnableSensitiveDataLogging()
.UseLoggerFactory(lf);
}
I suspect if I was using GenericHost
things 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).
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | Richard |