EFCore记录慢查询日志
记录慢查询日志
基于.NET6创建API项目,安装WJChi.Net.EFCoreSlowQuery包,示例代码如下:
using Api.Database; using EFCoreExtensions.Middlewares; using Microsoft.EntityFrameworkCore; var builder = WebApplication.CreateBuilder(args); // Add services to the container. builder.Services.AddControllers(); builder.Services.AddDbContext<InfoDbContext>(opt => { opt.UseSqlServer("Server = localhost;Database = Demo;User ID = sa;Password = Docker2022!;Application Name = EFCore;"); }); var app = builder.Build(); // Configure the HTTP request pipeline. // Configuration via code app.UseEFCoreSlowQuery(opt => { opt.ServiceName = "Demo APIs"; opt.SlowQueryThresholdMilliseconds = 20; }); app.MapControllers(); app.Run();
也支持通过配置文件进行配置:
builder.Services.Configure<EFCoreSlowQueryOptions>(builder.Configuration.GetSection(EFCoreSlowQueryOptions.OptionsName));
app.UseEFCoreSlowQuery();
配置文件内容如下:
{ "EFCoreSlowQuery": { "ServiceName": "Demo APIs", "SlowQueryThresholdMilliseconds": 20 } }
输出如下:
推荐阅读
How to identify slow running queries in SQL Server
Overview of Logging and Interception