...

/

Filtering Logs in Entity Framework Core

Filtering Logs in Entity Framework Core

Learn how to filter logs using simple logging in EF Core.

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)
        {
        }

    }

}
Filtering by log level

Click the “Run” button in the project above, then execute the command below in the terminal:

Press + to interact
dotnet run

Below is a snippet from the output:

Press + to interact
info: 12/13/2022 08:04:17.264 CoreEventId.ContextInitialized[10403] (Microsoft.EntityFrameworkCore.Infrastructure)
Entity Framework Core 6.0.2 initialized 'ArtistsContext' using provider 'Microsoft.EntityFrameworkCore.Sqlite:6.0.2' with options: None
info: 12/13/2022 08:04:17.517 RelationalEventId.CommandExecuted[20101] (Microsoft.EntityFrameworkCore.Database.Command)
Executed DbCommand (6ms) [Parameters=[@p0='?' (DbType = Int64), @p1='?' (Size = 5), @p2='?' (Size = 9)], CommandType='Text', CommandTimeout='30']
INSERT INTO "Employees" ("Age", "FirstName", "LastName")
VALUES (@p0, @p1, @p2);
SELECT "Id"
FROM "Employees"
WHERE changes() = 1 AND "rowid" = last_insert_rowid();

Note the following:

  • On ...