記錄Logging

提示

您可以在 GitHub 上檢視此文章的範例 (英文)。You can view this article's sample on GitHub.

ASP.NET Core 應用程式ASP.NET Core applications

EF Core 自動記錄與機制整合的 ASP.NET Core 每當AddDbContextAddDbContextPool用。EF 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 需要其本身設定一或多個 ILoggerProvider ILoggerFactory。EF Core logging currently requires an ILoggerFactory which is itself configured with one or more ILoggerProvider. 常見的提供者都隨附在下列套件:Common providers are shipped in the following packages:

安裝適當的套件之後, 應用程式應該建立 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 LoggerFactory MyLoggerFactory
    = new LoggerFactory(new[] {new ConsoleLoggerProvider((_, __) => true, true)});

這個單一/全域執行個體應該然後再註冊 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 easiest way to filter what is logged is to configure it when registering the ILoggerProvider. 例如: For example:

public static readonly LoggerFactory MyLoggerFactory
    = new LoggerFactory(new[]
    {
        new ConsoleLoggerProvider((category, level)
            => category == DbLoggerCategory.Database.Command.Name
               && level == LogLevel.Information, true)
    });

在此範例中,記錄檔會篩選傳回只有訊息:In this example, the log is filtered to return only messages:

  • 在 'Microsoft.EntityFrameworkCore.Database.Command' 類別in the 'Microsoft.EntityFrameworkCore.Database.Command' category
  • 在 「 資訊 」 層級at the 'Information' level

記錄器類別目錄中的定義 EF CoreDbLoggerCategory類別,以讓您輕鬆尋找類別目錄,但這些解析成簡單字串。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.