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

如何禁用Entity Framework对DbUpdateConcurrencyException的日志记录?

解决EF Core记录已处理的DbUpdateConcurrencyException日志问题

你之前的配置无效,是因为DbUpdateConcurrencyException对应的EF日志事件ID是CoreEventId.DbUpdateConcurrencyException,而非CoreEventId.OptimisticConcurrencyException(后者用于乐观并发检查的其他场景)。以下是两种有效的禁用该日志的方法:

方法一:在DbContext配置中过滤日志

直接在AddDbContext的配置里,通过LogTo的过滤参数排除目标事件ID:

services.AddDbContext<IdentityDbContext>(options =>
{
    options
        .UseSqlServer(connectionString)
        .LogTo(
            // 替换为你的常规日志输出逻辑,比如写入日志框架
            message => Console.WriteLine(message),
            filter: (eventId, level) => eventId.Id != CoreEventId.DbUpdateConcurrencyException.Id
        );
});

如果希望完全忽略该事件的日志,也可以给LogTo传递空委托并指定仅包含该事件(相当于不输出任何内容):

services.AddDbContext<IdentityDbContext>(options =>
{
    options
        .UseSqlServer(connectionString)
        .LogTo(_ => { }, new[] { CoreEventId.DbUpdateConcurrencyException });
});

方法二:全局日志过滤

在程序的全局日志配置中,针对EF Core的日志排除目标事件ID,适合需要统一管理多个DbContext日志规则的场景:

// 在Program.cs(或Startup.cs的ConfigureLogging方法中)
builder.Logging.AddFilter(
    "Microsoft.EntityFrameworkCore",
    (eventId, level) => eventId.Id != CoreEventId.DbUpdateConcurrencyException.Id
);

注意:CoreEventId.DbUpdateConcurrencyException的ID值为10000,你也可以直接用数值判断,但建议使用枚举值以保证可读性和版本兼容性。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.29 19:42:28