Skip to content

Instantly share code, notes, and snippets.

@karenpayneoregon
Created August 14, 2025 13:52
Show Gist options
  • Select an option

  • Save karenpayneoregon/4458622ab55979fded368d3f786febe1 to your computer and use it in GitHub Desktop.

Select an option

Save karenpayneoregon/4458622ab55979fded368d3f786febe1 to your computer and use it in GitHub Desktop.
EF Core slow query Interceptor

Original code from X @Dave_DotNet modified to use Serilog for when a slow query is detected

using Serilog;
using static System.DateTime;
namespace TODO.Classes;
public class SetupLogging
{
public static void Development()
{
Log.Logger = new LoggerConfiguration()
.WriteTo.File(Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "LogFiles", $"{Now.Year}-{Now.Month}-{Now.Day}", "Log.txt"),
rollingInterval: RollingInterval.Infinite,
outputTemplate: "[{Timestamp:yyyy-MM-dd HH:mm:ss.fff} [{Level}] {Message}{NewLine}{Exception}")
.CreateLogger();
}
}
using System.Data.Common;
using Microsoft.EntityFrameworkCore.Diagnostics;
using Serilog;
namespace TODO.Classes;
public class SlowQueryInterceptor : DbCommandInterceptor
{
private const int SlowQueryThreshold = 200; // Threshold in milliseconds
public override DbDataReader ReaderExecuted(DbCommand command, CommandExecutedEventData eventData, DbDataReader result)
{
if (eventData.Duration.TotalMilliseconds > SlowQueryThreshold)
{
Log.Information("Slow query detected: {CommandText}", command.CommandText);
}
return base.ReaderExecuted(command, eventData, result);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment