I\'m using EF 6.0 with LINQ in MVC 5 project. I want to log all the SQL queries executed by the Entity Framework DbContext for debugging/performance-measurement purpose.
EF Core logging automatically integrates with the logging mechanisms of .NET Core. Example how it can be used to log to console:
public class SchoolContext : DbContext
{
//static LoggerFactory object
public static readonly ILoggerFactory loggerFactory = new LoggerFactory(new[] {
new ConsoleLoggerProvider((_, __) => true, true)
});
//or
// public static readonly ILoggerFactory loggerFactory = new LoggerFactory().AddConsole((_,___) => true);
public SchoolContext():base()
{
}
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{
optionsBuilder.UseLoggerFactory(loggerFactory) //tie-up DbContext with LoggerFactory object
.EnableSensitiveDataLogging()
.UseSqlServer(@"Server=.\SQLEXPRESS;Database=SchoolDB;Trusted_Connection=True;");
}
public DbSet Students { get; set; }
}
If you would like to log to output window use this instead:
public static readonly ILoggerFactory loggerFactory = new LoggerFactory(new[] {
new DebugLoggerProvider()
});
https://www.entityframeworktutorial.net/efcore/logging-in-entityframework-core.aspx