EF Core Uses Simple Logging to Output Logs

EF Core Uses Simple Logging to Output Logs

When using EF Core, many times you need to know what SQL statements EF Core actually executes.

Last updated 5/4/2022 3:56 PM
MyIO
2 min read
Category
EF Core
Tags
.NET C# EF Core ORM

When using EF Core, there are many times when you need to know what SQL statements EF Core actually executes.

Simple Logging is a feature provided by EF Core that can be used to easily obtain logs when developing and debugging applications. This form of logging requires minimal configuration and does not require additional NuGet packages.

Feature Overview

It is very simple to configure, just call the LogTo method in the DbContext.OnConfiguring implementation:

public class DefaultDbContext : DbContext
{
    protected override void OnConfiguring(DbContextOptionsBuilder options)
    {
        ...

        options.LogTo(Console.WriteLine);
    }
    ...
}

LogTo requires an Action delegate that accepts a string, such as Console.WriteLine. You can also write custom methods to decide how to output logs.

Filtering

By default, Simple Logging records every log at Debug level or higher. This can result in too many logs being output, which is not helpful for debugging. You can limit it to only log at Information level or higher:

options.LogTo(Console.WriteLine,
    Microsoft.Extensions.Logging.LogLevel.Information);

Query Tags

However, this can still generate many logs. At this point, we can combine query tags to help us quickly locate the needed logs:

var users = context.User.TagWith("查询所有用户").ToList();

Keep Exploring

Related Reading

More Articles