在ASP.NET Core使用Entity Framework Core的日志
在开发中,我们想在调试中查看EF Core执行的sql语句,可以使用SQL Studio Manager Tools工具,另一种方式是使用EF Core提供的日志。
在ASP.NET Core使用Entity Framework Core的日志的步骤:
1. 设置启动方式
在launchSettings.json中删除IIS节点,使程序以控制台应用启动。
2. 在Programm.cs配置日志
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
namespace CompanyApp
{
public class Program
{
public static void Main(string[] args)
{
CreateHostBuilder(args).Build().Run();
}
public static IHostBuilder CreateHostBuilder(string[] args) =>
Host.CreateDefaultBuilder(args)
.ConfigureLogging((hostingContext, logging) =>
{
logging.AddConfiguration(hostingContext.Configuration.GetSection("Logging"));
logging.AddConsole();
logging.AddDebug();
logging.AddEventSourceLogger();
})
.ConfigureWebHostDefaults(webBuilder =>
{
webBuilder.UseStartup<Startup>();
});
}
}
3. 默认日志不显示敏感数据,这样查看不到sql语句执行的参数,如果想看到参数,需要在Startup.cs的ConfigureServices方法中启用显示敏感数据:
public void ConfigureServices(IServiceCollection services)
{
services.AddControllersWithViews();
services.AddDbContext<CompanyDbContext>(options => {
//启用显示敏感数据
options.EnableSensitiveDataLogging(true);
options.UseSqlServer(Configuration.GetConnectionString("CompanyDbContext"));
});
}
4. 配置appsettings.json日志选项:
{
"Logging": {
"LogLevel": {
"Default": "Information",
"Microsoft": "Warning",
"Microsoft.Hosting.Lifetime": "Information",
"Microsoft.EntityFrameworkCore.Database.Command": "Information"
}
},
"AllowedHosts": "*",
"ConnectionStrings": {
"CompanyDbContext": "Server=(localdb)\\mssqllocaldb;Database=CompanyDb;Trusted_Connection=True;MultipleActiveResultSets=true"
}
}