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();
