vmg*_*vmg 17 entity-framework .net-core
我有一个使用实体框架核心的控制台.net核心应用程序.该应用程序使用日志框架写入文件和控制台:
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>();
Run Code Online (Sandbox Code Playgroud)
文件输出的最低级别设置为"信息".但是这个设置输出也包含SQL查询,这里是一个例子:
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]
有没有办法禁用SQL查询日志记录(仅在调试日志级别记录它们)
Mic*_*kov 76
发现如果按以下方式修改日志记录部分,我将看不到与 SQL 查询相关的 EF 日志消息:
"Logging": {
"LogLevel": {
"Default": "Information",
"Microsoft": "Information",
"Microsoft.Hosting.Lifetime": "Information",
"Microsoft.EntityFrameworkCore.Database.Command": "Warning"
}
}
Run Code Online (Sandbox Code Playgroud)
lam*_*idu 21
如果您使用的是内置记录器,则可以在Program.cs中为ILoggingBuilder添加过滤器.
所以,它看起来像:
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();
Run Code Online (Sandbox Code Playgroud)
不知道这是否仍然是一个活跃的问题,但这是我的解决方案,请覆盖“ Microsoft.EntityFrameworkCore.Database.Command”的最低级别
Log.Logger = new LoggerConfiguration()
.MinimumLevel.ControlledBy(loggingLevelSwitch)
.MinimumLevel.Override("Microsoft.EntityFrameworkCore.Database.Command", Serilog.Events.LogEventLevel.Warning)
.Enrich.WithProperty("app", environment.ApplicationName)
.Enrich.FromLogContext()
.WriteTo.RollingFile($"./Logs/{environment.ApplicationName}")
.CreateLogger();
Run Code Online (Sandbox Code Playgroud)
如果您使用的是默认 Logger,则在appsettings.json(或appesttings.Development.json用于开发启动)文件中:
"Logging": {
"LogLevel": {
"Default": "Debug",
"System": "Information",
"Microsoft": "Warning" <----
}
},
Run Code Online (Sandbox Code Playgroud)
将其设置为Warning而不是Information。
您想更改 Serilog 配置以将Microsoft.EntityFrameworkCore.Storage.IRelationalCommandBuilderFactory上下文的最低级别设置为Warning或更高。
您可以通过将输出模板设置为类似[{Timestamp:HH:mm:ss} {SourceContext} [{Level}] {Message}{NewLine}{Exception}. 一旦您知道上下文,您就可以将模板设置回之前的状态。