Logging

Tip

You can view this article's sample on GitHub.

Simple logging

Note

This feature was added in EF Core 5.0.

Entity Framework Core (EF Core) generates log messages for operations such as executing a query or saving changes to the database. These can be accessed from any type of application through use of LogTo when configuring a DbContext instance. This configuration is commonly done in an override of DbContext.OnConfiguring. For example:

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

This concept is similar to Database.Log in EF6.

See Simple Logging for more information.

ASP.NET Core applications

EF Core integrates automatically with the logging mechanisms of ASP.NET Core whenever AddDbContext or AddDbContextPool is used. Therefore, when using ASP.NET Core, logging should be configured as described in the ASP.NET Core documentation.

Other applications

EF Core logging requires an ILoggerFactory which is itself configured with one or more logging providers. Common providers are shipped in the following packages:

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

This 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");

Warning

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

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:

  • in the 'Microsoft.EntityFrameworkCore.Database.Command' category
  • at the 'Information' level

For EF Core, logger categories are defined in the DbLoggerCategory class to make it easy to find categories, but these resolve to simple strings.

More details on the underlying logging infrastructure can be found in the ASP.NET Core logging documentation.