3.0 RTM及更高版本的更新:日志级别已恢复为信息。请查看文档中的
过滤日志内容以获取更多详细信息。还可以参考
appsettings.json
中可用于过滤的
类别列表。
EF Core在Debug级别记录日志,但主机构建器使用的默认级别是Information。因此,必须手动将日志级别设置为Trace或Debug。
默认情况下,此代码不会记录任何EF事件。
static async Task Main(string[] args)
{
var host = Host
.CreateDefaultBuilder(args)
.ConfigureServices((context, services) =>
{
var configuration = context.Configuration;
services.AddDbContext<MyContext>(options =>
options.UseSqlServer(configuration.GetConnectionString("someConnection")));
})
.Build();
using (var ctx = host.Services.GetRequiredService<MyContext>())
{
var cnt = await ctx.Customers.CountAsync();
Console.WriteLine(cnt);
}
}
只会记录这个事件:
info: Microsoft.EntityFrameworkCore.Infrastructure[10403]
Entity Framework Core 3.0.0-preview6.19304.10 initialized 'ConsolidatorsContext' using provider 'Microsoft.EntityFrameworkCore.SqlServer' with options: None
要记录EF事件,我们需要通过
appsettings.json
或代码将EF Core事件的日志级别更改为
Trace
或
Debug
。例如,在
appsettings.json
中包含以下内容:
"Logging": {
"LogLevel": {
"Microsoft.EntityFrameworkCore":"Debug"
}
},
将记录EF事件:
dbug: Microsoft.EntityFrameworkCore.Infrastructure[10401]
An 'IServiceProvider' was created for internal use by Entity Framework.
info: Microsoft.EntityFrameworkCore.Infrastructure[10403]
Entity Framework Core 3.0.0-preview6.19304.10 initialized 'MyContext' using provider 'Microsoft.EntityFrameworkCore.SqlServer' with options: None
dbug: Microsoft.EntityFrameworkCore.Database.Connection[20000]
Opening connection to database 'Customers' on server '10.0.0.216'.
dbug: Microsoft.EntityFrameworkCore.Database.Connection[20001]
Opened connection to database 'Customers' on server '10.0.0.216'.
dbug: Microsoft.EntityFrameworkCore.Database.Command[20100]
Executing DbCommand [Parameters=[], CommandType='Text', CommandTimeout='30']
SELECT COUNT(*)
FROM [Customers] AS [c]
dbug: Microsoft.EntityFrameworkCore.Database.Command[20101]
Executed DbCommand (42ms) [Parameters=[], CommandType='Text', CommandTimeout='30']
SELECT COUNT(*)
FROM [Customers] AS [c]
4
dbug: Microsoft.EntityFrameworkCore.Database.Command[20300]
A data reader was disposed.
dbug: Microsoft.EntityFrameworkCore.Database.Connection[20002]
Closing connection to database 'Customers' on server '10.0.0.216'.
dbug: Microsoft.EntityFrameworkCore.Database.Connection[20003]
Closed connection to database 'Customers' on server '10.0.0.216'.
dbug: Microsoft.EntityFrameworkCore.Infrastructure[10407]
'MyContext' disposed.