Filtering Logs in Entity Framework Core
Explore how to filter log outputs in Entity Framework Core by using log levels and message categories. Understand how to enable sensitive data logging to include parameter values in logs for more effective debugging of database interactions.
We'll cover the following...
Overview
We can filter the output of the logs to only include specific information.
Filtering by log levels
The table below shows the log levels that simple logging uses.
Log Levels
Log Level | Severity | Description |
Trace | 0 | Logs detailed messages. They may contain sensitive data and should not be used in production. |
Debug | 1 | Logs messages useful for interactive debugging purposes during development. |
Information | 2 | Logs messages that track the flow of the application. |
Warning | 3 | Logs messages that indicate abnormal or unexpected events in the application flow. |
Error | 4 | Logs messages that indicate a failure in the current flow of an application. |
Critical | 5 | Logs messages that indicate a system crash and require immediate attention. |
We can filter by log level. By default, the output from simple logging includes every message at the Debug level and above. We can pass the desired minimum level to the LogTo method. We’ll demonstrate using the C# project below:
using Microsoft.EntityFrameworkCore;
namespace Logging
{
public class ArtistsContext : DbContext
{
public ArtistsContext() { }
public ArtistsContext(DbContextOptions<ArtistsContext> options) : base(options) { }
public virtual DbSet<Employee> Employees { get; set; }
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{
if (!optionsBuilder.IsConfigured)
{
optionsBuilder
.UseSqlite("data source=output/Artists.db")
.LogTo(
Console.WriteLine,
Microsoft.Extensions.Logging.LogLevel.Information
);
}
}
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
}
}
}Click the “Run” button in the ...