مخزن جامع کدها و الگوهای توسعه

اسنیپت‌ها، ترفندها و کدهای کاربردی

مجموعه‌ای منتخب از ساختارهای کد، پیکربندی‌های بهینه، پیش‌نیازها و کدهای همراه برای زبان‌ها و فریم‌ورک‌های مختلف.

۱ کد انتخاب شده
دسته‌بندی: بهینه‌سازی کارایی و اینترسپتورها اینترسپتور اختصاصی برای کشف و ثبت لاگ کوئری‌های کند (Slow Query Interceptor)
پاکسازی همه فیلترها
بهینه‌سازی کارایی و اینترسپتورها CSHARP 1405/06/30

اینترسپتور اختصاصی برای کشف و ثبت لاگ کوئری‌های کند (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)
csharp
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)
مشاهده کد
csharp
// Program.cs - نحوه ثبت اینترسپتور در زنجیره سرویس‌های DI
builder.Services.AddSingleton<SlowQueryLogInterceptor>();
builder.Services.AddDbContext<AppDbContext>((serviceProvider, options) =>
{
    options.UseSqlServer(connectionString)
           .AddInterceptors(serviceProvider.GetRequiredService<SlowQueryLogInterceptor>());
});
نکات کلیدی و ترفندها (Tips & Notes)
برای جلوگیری از سربار حافظه در پروداکشن، از ثبت لاگ پارامترهای حساس خودداری کنید و آستانه زمانی را بر اساس SLA پروژه (بین ۳۰۰ تا ۱۰۰۰ میلی‌ثانیه) تنظیم نمایید.