You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用NLog时如何抑制EF Core的SQL日志输出?

问题

尝试让EF Core停止将SQL执行日志写入日志文件,当前使用NLog作为日志组件。已在appsettings.json配置日志级别、在DbContext创建时配置警告日志规则、添加日志服务时设置过滤规则,但仍会记录INFO级别的SQL执行日志,求排查遗漏的配置。

已尝试的配置

appsettings.json 配置

"Logging":
{
    "LogLevel":
    {
        "Default": "Information",
        "Microsoft": "Warning",
        "Microsoft.Hosting.Lifetime": "Information",
        "Microsoft.AspNetCore": "Warning",
        "Microsoft.EntityFrameworkCore.Database.Command": "Warning"
    }
},

DbContext 配置代码

services.AddDbContext<TContext>(o =>
{
    o.UseSqlServer(connectionString);
    o.ConfigureWarnings(c => c.Log((RelationalEventId.CommandExecuting, LogLevel.Warning)));
});

日志服务配置代码

services.AddLogging(logging =>
{
    logging.ClearProviders();
    logging.SetMinimumLevel(LogLevel.Trace);
    logging.AddConfiguration(configuration.GetSection("Logging"));
    logging.AddNLog();
    logging.AddFilter("Microsoft", LogLevel.Warning);
});

仍出现的日志

2024-11-20 15:13:36.3284||INFO|Microsoft.EntityFrameworkCore.Database.Command|Executed DbCommand (34ms)...
解决方案

以下是你可能遗漏的配置点及修正方法:

  • 区分CommandExecuting和CommandExecuted事件
    你在ConfigureWarnings中只修改了CommandExecuting事件的日志级别,但实际产生日志的是CommandExecuted事件(对应日志里的Executed DbCommand)。需要将该事件也纳入配置:

    o.ConfigureWarnings(c => 
    {
        c.Log((RelationalEventId.CommandExecuting, LogLevel.Warning));
        c.Log((RelationalEventId.CommandExecuted, LogLevel.Warning));
    });
    
  • 检查NLog自身的过滤规则
    NLog可能绕过.NET Core的日志过滤直接记录日志,需要在NLog配置文件(如nlog.config)中添加针对性过滤:

    <rules>
        <!-- 其他日志规则 -->
        <logger name="Microsoft.EntityFrameworkCore.Database.Command" minlevel="Warn" writeTo="你的日志目标" />
        <!-- 若要直接屏蔽,可改为:<logger name="Microsoft.EntityFrameworkCore.Database.Command" final="true" /> -->
    </rules>
    
  • 调整日志服务配置顺序
    当前先加载配置再添加NLog,可能导致NLog未正确应用配置,建议调整顺序:

    services.AddLogging(logging =>
    {
        logging.ClearProviders();
        logging.SetMinimumLevel(LogLevel.Trace);
        logging.AddNLog(); // 先添加NLog
        logging.AddConfiguration(configuration.GetSection("Logging")); // 再应用配置
        logging.AddFilter("Microsoft", LogLevel.Warning);
    });
    
  • 排查其他配置源
    检查是否存在其他配置入口(如代码中单独设置的过滤器、环境变量日志配置)覆盖了当前规则,确保所有配置源都将Microsoft.EntityFrameworkCore.Database.Command的日志级别设为Warning或更高。


内容的提问来源于stack exchange,提问作者Tyrel Van Niekerk

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.16 05:06:06