在实体框架核心中抑制 SQL 查询日志记录 [英] Suppress SQL Queries logging in Entity Framework core
问题描述
我有一个使用实体框架核心的控制台 .net 核心应用程序.该应用程序使用日志记录框架写入文件和控制台:
I have a console .net core app that uses entity framework core. The app uses logging framework to write to file and console:
serviceProvider = new ServiceCollection()
.AddLogging()
.AddDbContext<DataStoreContext>(options =>
options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection")))
.BuildServiceProvider();
//configure console logging
serviceProvider.GetService<ILoggerFactory>()
.AddConsole(LogLevel.Debug)
.AddSerilog();
Log.Logger = new LoggerConfiguration()
.MinimumLevel.Information()
.WriteTo.RollingFile(Path.Combine(Directory.GetCurrentDirectory(), "logs/vcibot-{Date}.txt"))
.WriteTo.RollingFile(Path.Combine(Directory.GetCurrentDirectory(), "logs/vcibot-errors-{Date}.txt"), LogEventLevel.Error)
.CreateLogger();
logger = serviceProvider.GetService<ILoggerFactory>()
.CreateLogger<Program>();
文件输出的最小级别设置为信息.但是使用此设置输出还包含 SQL 查询,示例如下:
Min Level for file output is set to Information. But with this setup output also contains SQL queries, here is the example:
2017-02-06 10:31:38.282 -08:00 [信息] 执行的 DbCommand (0ms)[Parameters=[], CommandType='Text', CommandTimeout='30'] SELECT[f].[BuildIdentifier], [f].[Branch], [f].[BuildDate],[f].[StaticAssetSizeInKb] FROM [FileSizesHistoryEntries] AS [f]
2017-02-06 10:31:38.282 -08:00 [Information] Executed DbCommand (0ms) [Parameters=[], CommandType='Text', CommandTimeout='30'] SELECT [f].[BuildIdentifier], [f].[Branch], [f].[BuildDate], [f].[StaticAssetSizeInKb] FROM [FileSizesHistoryEntries] AS [f]
有没有办法禁用 SQL 查询日志记录(仅在调试日志级别记录它们)
Is there a way to disable the SQL queries logging (log them only in Debug log level)
推荐答案
如果您使用内置记录器,您可以在 Program.cs 中为您的 ILoggingBuilder 添加过滤器.
If you're using built-in logger, you can add filter to you ILoggingBuilder in Program.cs.
所以,它看起来像:
WebHost.CreateDefaultBuilder(args)
// ...
.ConfigureLogging((context, logging) => {
var env = context.HostingEnvironment;
var config = context.Configuration.GetSection("Logging");
// ...
logging.AddConfiguration(config);
logging.AddConsole();
// ...
logging.AddFilter("Microsoft.EntityFrameworkCore.Database.Command", LogLevel.Warning);
})
// ...
.UseStartup<Startup>()
.Build();
这篇关于在实体框架核心中抑制 SQL 查询日志记录的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!