You can view this article’s sample on GitHub.
ASP.NET Core applications
EF Core integrates automatically with the logging mechanisms of ASP.NET Core whenever
AddDbContextPool is used. Therefore, when using ASP.NET Core, logging should be configured as described in the ASP.NET Core documentation.
EF Core logging currently requires an ILoggerFactory which is itself configured with one or more ILoggerProvider. 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 LoggerFactory MyLoggerFactory = new LoggerFactory(new new ConsoleLoggerProvider((_, __) => true, true));
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");
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 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:
- 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.