【问题标题】:Enable raw SQL logging in Entity Framework Core在 Entity Framework Core 中启用原始 SQL 日志记录
【发布时间】:2017-01-10 00:17:38
【问题描述】:

如何启用 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);
}

我期待看到这样的东西:

Microsoft.EntityFrameworkCore.Storage.Internal.RelationalCommandBuilder...
SELECT [t].[Id], [t].[DateCreated], [t].[Name], [t].[UserName]
FROM [Trips] AS [t]

【问题讨论】:

    标签: c# entity-framework


    【解决方案1】:

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

    "Logging": {
      "LogLevel": {
        "Default": "Debug",
        "System": "Information",
        "Microsoft": "Information"
      }
    }
    

    【讨论】:

      【解决方案2】:

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

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

      【讨论】:

      • 请注意阅读上述代码的其他人:_loggerFactory 参数是使用 FooContext 类中的构造函数依赖注入设置的。
      • 仅供其他遇到相同问题的人阅读this article。因为这个答案不是很有帮助。
      • 如果你使用asp.net mvc core,不需要做任何事情,只要确保日志记录的详细程度是“信息”。
      • @meze 如果您使用services.AddDbContext(...) 注册您的DbContext,无论您是否使用.NET Core 都无关紧要。此方法确保应用程序标准日志记录工厂已注册,如果找不到,则会引发异常。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-02-28
      相关资源
      最近更新 更多