在Entity Framework Core中启用原始SQL日志记录

cod*_*rsl 9 c# entity-framework

如何启用DbCommand原始SQL查询的日志记录?

我已将以下代码添加到我的Startup.cs文件中,但未看到Entity Framework Core中的任何日志条目.

void ConfigureServices(IServiceCollection services)
{
    services.AddLogging();
}

public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
{
    loggerFactory.AddConsole(Configuration.GetSection("Logging"));
    loggerFactory.AddDebug(LogLevel.Debug);
}
Run Code Online (Sandbox Code Playgroud)

我期待看到这样的事情:

Microsoft.EntityFrameworkCore.Storage.Internal.RelationalCommandBuilder...
SELECT [t].[Id], [t].[DateCreated], [t].[Name], [t].[UserName]
FROM [Trips] AS [t]
Run Code Online (Sandbox Code Playgroud)

小智 6

从 MVC Core 2 开始,记录 SQL 是默认行为。只需确保 appSettings json 文件中的日志记录级别正确即可。

"Logging": {
  "LogLevel": {
    "Default": "Debug",
    "System": "Information",
    "Microsoft": "Information"
  }
}
Run Code Online (Sandbox Code Playgroud)


cod*_*rsl 3

想通了 - 需要配置 DbContext 以使用记录器工厂。

protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{
    base.OnConfiguring(optionsBuilder);

    optionsBuilder.UseLoggerFactory(_loggerFactory);
}
Run Code Online (Sandbox Code Playgroud)

  • 对于其他遇到同样问题的人来说,请阅读[本文](https://learn.microsoft.com/en-us/ef/core/miscellaneous/logging)。因为这个答案不是很有帮助。 (7认同)
  • 请注意阅读上述代码的其他人:“_loggerFactory”参数是使用“FooContext”类中的构造函数依赖注入来设置的。 (2认同)