如何将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
相关产品推荐
相关产品推荐

