EF Core uses Simple Logging to output logs

EF Core uses Simple Logging to output logs

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

最后更新 5/4/2022 3:56 PM
MyIO
预计阅读 2 分钟
分类
EF Core
标签
.NET C# EF Core ORM

When using EF Core, you often 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 while developing and debugging applications. This form of logging requires minimal configuration and no other NuGet packages are required.

A glimpse of functions

配置起来非常简单,只需在DbContext.OnConfiguring实现中调用LogTo方法即可:

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

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

LogTo需要一个 Action 委托接受字符串,比如Console.WriteLine,你也可以编写自定义方法决定如何输出日志。

screening

By default, Simple Logging records every log at a Debug level or higher. This will result in too many output logs, which is not helpful for debugging. You can limit the recording of only Information or higher-level logs:

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

inquiry indicia

但是,这样还是会产生很多日志。这时我们可以结合查询标记,帮助我们快速定位到需要的日志:

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

Keep Exploring

延伸阅读

更多文章