2. EF Core 如何显示执行的SQL语句

调试的时候需要查看执行的SQL 语句,我一般是使用 SQL Profiler,当然还有另外一种方式,就是配置EF 日志,这两种方式都比较简单实用,SQL Profiler可以过滤掉很多自己不想看的日志,可以只看某一个IP的日志,而EF Core 的日志则不可以;

SQL Profiler

TODO 我会在这里添加一个附件,以后使用记得修改hostname

EF Core 日志

设置启动方式

在launchSettings.json中删除IIS节点,使程序以控制台应用启动

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

启用显示敏感数据

默认是只能看到参数,看不到参数的值,在startup.cs 的ConfigureServices 方法中启用显示敏感数据:

public void ConfigureServices(IServiceCollection services)
{
    services.AddControllersWithViews();

    services.AddDbContext<CompanyDbContext>(options => {
        //启用显示敏感数据
        options.EnableSensitiveDataLogging(true);
        options.UseSqlServer(Configuration.GetConnectionString("CompanyDbContext"));
    });
}

配置 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"
  }
}
posted @ 2020-07-22 14:04  maanshancss  阅读(917)  评论(0编辑  收藏  举报