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

如何将Failed DbCommand日志从错误级别改为警告级别?

问题

我有一个已知的查询问题,希望仅将其记录为警告日志。但每次错误发生时,会先生成一条级别为错误的“Failed executing DbCommand”日志条目,之后才是我自定义的警告日志。请问是否有办法确保“Failed executing DbCommand”仅以警告级别记录?

现有代码

try
{
    _context.Objects.Add(@object);
}
catch(DbUpdateException ex) 
{
    log.Warning("Warning DbUpdate Exception error details:" + ex.Message);
}

当前日志输出

日志条目1(错误级别)

Failed executing DbCommand

INSERT INTO myTable

日志条目2(警告级别)

Warning: DbUpdate exception error details: blah

解决方案

要修改EF Core输出的“Failed executing DbCommand”日志级别,需通过日志过滤规则或EF Core专属配置调整:

方法1:注册DbContext时指定EF日志级别

在配置DbContext时,将Microsoft.EntityFrameworkCore.Database.Command类别的日志级别设为Warning:

services.AddDbContext<YourDbContext>(options =>
{
    options.UseSqlServer("你的连接字符串")
           .LogTo(logger => {}, LogLevel.Warning, new[] { DbLoggerCategory.Database.Command.Name });
});

方法2:全局日志过滤配置

如果使用.NET内置日志系统或Serilog等第三方日志框架,可通过全局配置过滤该类别的日志级别:

内置日志系统(appsettings.json)

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

Serilog框架配置

Log.Logger = new LoggerConfiguration()
    .MinimumLevel.Information()
    .Filter.ByIncludingOnly(logEvent => 
        !(logEvent.LoggerName == "Microsoft.EntityFrameworkCore.Database.Command" && 
          logEvent.Level == LogLevel.Error))
    .WriteTo.Console()
    .CreateLogger();

说明

EF Core默认会将执行失败的DbCommand日志以Error级别输出,通过上述配置可将该类别的日志级别强制调整为Warning,避免生成错误级别的“Failed executing DbCommand”日志,与自定义警告日志保持一致。

内容的提问来源于stack exchange,提问作者TheProgrammer

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.30 02:05:02