3.0 RTM 及更高版本的更新:日志级别恢复为信息。查看过滤记录的内容 https://learn.microsoft.com/ef/core/logging-events-diagnostics/extensions-logging?tabs=v3#filtering-and-other-configuration在文档中了解更多详细信息。另请参阅类别列表 https://learn.microsoft.com/ef/core/logging-events-diagnostics/simple-logging#message-categories可用于过滤appsettings.json
.
EF Core 日志位于Debug
level,但主机构建器使用的默认级别是Information
。因此,必须手动将日志记录级别设置为Trace
or 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 事件,我们需要将 EF Core 事件的日志记录级别更改为Trace
or Debug
通过appsettings.json
或代码。例如,将其包含在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.