اینترسپتور اختصاصی برای کشف و ثبت لاگ کوئریهای کند (Slow Query Interceptor) (Custom DbCommandInterceptor for Slow Query Logging in EF Core)
با اتصال این اینترسپتور به DbContext، تمام کوئریهایی که اجرای آنها در دیتابیس بیشتر از آستانه مشخص (مثلاً ۵۰۰ میلیثانیه) زمان ببرد بلافاصله شناسایی و لاگ میشوند بدون اینکه نیازی به تغییر کدهای ریپازیتوری باشد.
Intercepts all EF Core database commands and logs warnings when execution time exceeds the configured threshold, pinpointing slow queries in production.
پیشنیازها و وابستگیها (Dependencies)
Microsoft.EntityFrameworkCore.Relational (>= 8.0)public class SlowQueryLogInterceptor(ILogger<SlowQueryLogInterceptor> logger, long thresholdMilliseconds = 500)
: DbCommandInterceptor
{
public override DbDataReader ReaderExecuted(
DbCommand command,
CommandExecutedEventData eventData,
DbDataReader result)
{
CheckAndLogSlowQuery(command, eventData);
return base.ReaderExecuted(command, eventData, result);
}
public override ValueTask<DbDataReader> ReaderExecutedAsync(
DbCommand command,
CommandExecutedEventData eventData,
DbDataReader result,
CancellationToken cancellationToken = default)
{
CheckAndLogSlowQuery(command, eventData);
return base.ReaderExecutedAsync(command, eventData, result, cancellationToken);
}
private void CheckAndLogSlowQuery(DbCommand command, CommandExecutedEventData eventData)
{
if (eventData.Duration.TotalMilliseconds > thresholdMilliseconds)
{
logger.LogWarning(
"هشدار کوئری کند! زمان اجرا: {Duration}ms | متن کوئری: {Query}",
eventData.Duration.TotalMilliseconds,
command.CommandText);
}
}
}
کد مکمل یا نمونه استفاده همراه (Companion / Setup Code)
مشاهده کد
// Program.cs - نحوه ثبت اینترسپتور در زنجیره سرویسهای DI
builder.Services.AddSingleton<SlowQueryLogInterceptor>();
builder.Services.AddDbContext<AppDbContext>((serviceProvider, options) =>
{
options.UseSqlServer(connectionString)
.AddInterceptors(serviceProvider.GetRequiredService<SlowQueryLogInterceptor>());
});
نکات کلیدی و ترفندها (Tips & Notes)
برای جلوگیری از سربار حافظه در پروداکشن، از ثبت لاگ پارامترهای حساس خودداری کنید و آستانه زمانی را بر اساس SLA پروژه (بین ۳۰۰ تا ۱۰۰۰ میلیثانیه) تنظیم نمایید.
پیشنیازها و کدهای پایه:
1 مورد
مراحل بعد و کدهای تکمیلی:
1 مورد