Interview Question
How can you enable logging of SQL queries generated by Entity Framework Core?
Answer
There are several ways to enable SQL query logging in EF Core:
1. Using LogTo Method
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{
optionsBuilder
.LogTo(Console.WriteLine) // Log to console
.EnableSensitiveDataLogging() // Optional: Include parameter values
.EnableDetailedErrors(); // Optional: More detailed error messages
}
2. Using Microsoft.Extensions.Logging
// In Program.cs or Startup.cs
builder.Services.AddDbContext<ApplicationDbContext>(options =>
options.UseSqlServer(connectionString)
.UseLoggerFactory(LoggerFactory.Create(builder =>
{
builder
.AddConsole()
.AddFilter((category, level) =>
category == DbLoggerCategory.Database.Command.Name &&
level == LogLevel.Information);
})));
3. Using ILoggerFactory in DbContext
public class ApplicationDbContext : DbContext
{
public static readonly ILoggerFactory MyLoggerFactory
= LoggerFactory.Create(builder =>
{
builder
.AddFilter((category, level) =>
category == DbLoggerCategory.Database.Command.Name &&
level == LogLevel.Information)
.AddConsole();
});
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{
optionsBuilder.UseLoggerFactory(MyLoggerFactory);
}
}
Key Points 💡
- LogTo is simplest for quick debugging
- ILoggerFactory is better for production use
- EnableSensitiveDataLogging shows parameter values
- Consider logging performance impact in production
Common Follow-up Questions
- How do you log queries to a file instead of console?
- How can you filter specific types of database operations?
- What’s the performance impact of query logging?
Test Your Knowledge
Take a quick quiz to test your understanding of this topic.