LoggingLogging

提示

可在 GitHub 上查看此文章的示例You can view this article's sample on GitHub.

简单的日志记录Simple logging

备注

此功能是在 EF Core 5.0 中添加的。This feature was added in EF Core 5.0.

Entity Framework Core (EF Core) 为操作(如执行查询或保存对数据库所做的更改)生成日志消息。Entity Framework Core (EF Core) generates log messages for operations such as executing a query or saving changes to the database. 可以通过使用LogTo从任何类型的应用程序访问这些应用程序These can be accessed from any type of application through use of LogTo 配置 DbContext 实例时。when configuring a DbContext instance. 此配置通常在的重写中完成 DbContext.OnConfiguringThis configuration is commonly done in an override of DbContext.OnConfiguring. 例如:For example:

protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
    => optionsBuilder.LogTo(Console.WriteLine);

此概念类似于 Database.Log EF6 中的。This concept is similar to Database.Log in EF6.

有关详细信息,请参阅 简单日志记录See Simple Logging for more information.

ASP.NET Core 应用程序ASP.NET Core applications

使用或时,EF Core 会自动与 ASP.NET Core 的日志记录机制集成 AddDbContext AddDbContextPoolEF Core integrates automatically with the logging mechanisms of ASP.NET Core whenever AddDbContext or AddDbContextPool is used. 因此,在使用 ASP.NET Core 时,应按 ASP.NET Core 文档中所述配置日志记录。Therefore, when using ASP.NET Core, logging should be configured as described in the ASP.NET Core documentation.

其他应用程序Other applications

EF Core 日志记录要求使用一个或多个日志记录提供程序配置的 ILoggerFactory。EF Core logging requires an ILoggerFactory which is itself configured with one or more logging providers. 常见的提供程序随附在以下包中:Common providers are shipped in the following packages:

在) (安装适当的包后,应用程序应创建 Server.loggerfactory 的单一实例/全局实例。After installing the appropriate package(s), the application should create a singleton/global instance of a LoggerFactory. 例如,使用控制台记录器:For example, using the console logger:

public static readonly ILoggerFactory MyLoggerFactory
    = LoggerFactory.Create(builder => { builder.AddConsole(); });

然后,应在上向 EF Core 注册此单一实例/全局实例 DbContextOptionsBuilderThis singleton/global instance should then be registered with EF Core on the DbContextOptionsBuilder. 例如:For example:

protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
    => optionsBuilder
        .UseLoggerFactory(MyLoggerFactory) // Warning: Do not create a new ILoggerFactory instance each time
        .UseSqlServer(
            @"Server=(localdb)\mssqllocaldb;Database=EFLogging;Trusted_Connection=True;ConnectRetryCount=0");

警告

对于每个上下文实例,应用程序不会创建新的 ILoggerFactory 实例,这一点非常重要。It is very important that applications do not create a new ILoggerFactory instance for each context instance. 这样做会导致内存泄漏和性能不佳。Doing so will result in a memory leak and poor performance.

筛选记录内容Filtering what is logged

应用程序可以通过在 ILoggerProvider 上配置筛选器来控制要记录的内容。The application can control what is logged by configuring a filter on the ILoggerProvider. 例如:For example:

public static readonly ILoggerFactory MyLoggerFactory
    = LoggerFactory.Create(builder =>
        {
            builder
                .AddFilter((category, level) =>
                    category == DbLoggerCategory.Database.Command.Name
                    && level == LogLevel.Information)
                .AddConsole();
        });

在此示例中,将筛选日志以仅返回消息:In this example, the log is filtered to only return messages:

  • 在 "Microsoft.entityframeworkcore" 类别中in the 'Microsoft.EntityFrameworkCore.Database.Command' category
  • 在 "信息" 级别at the 'Information' level

对于 EF Core,记录器类别在类中定义 DbLoggerCategory ,以方便查找类别,但这些类别解析为简单字符串。For EF Core, logger categories are defined in the DbLoggerCategory class to make it easy to find categories, but these resolve to simple strings.

有关基础日志记录基础结构的更多详细信息,请参阅 ASP.NET Core 日志记录文档More details on the underlying logging infrastructure can be found in the ASP.NET Core logging documentation.