Skip to content

Instantly share code, notes, and snippets.

@davepcallan
Last active January 2, 2025 19:22
Show Gist options
  • Save davepcallan/91d4cc9922b12e6f5c537effcdc173c2 to your computer and use it in GitHub Desktop.
Save davepcallan/91d4cc9922b12e6f5c537effcdc173c2 to your computer and use it in GitHub Desktop.
Finding slow queries with Entity Framework Interceptors
using Microsoft.EntityFrameworkCore.Diagnostics;
using System.Data.Common;
namespace EntityFrameworkExamples;
public class SlowQueryInterceptor(ILogger<SlowQueryInterceptor> logger) : DbCommandInterceptor
{
private const int _slowQueryThresholdInMilliseconds = 5; //from config
public override DbDataReader ReaderExecuted(
DbCommand command,
CommandExecutedEventData eventData,
DbDataReader result)
{
if (eventData.CommandSource == CommandSource.LinqQuery && eventData.Duration.TotalMilliseconds > _slowQueryThresholdInMilliseconds)
{
LogSlowQuery(command, eventData);
}
return base.ReaderExecuted(command, eventData, result);
}
public override ValueTask<DbDataReader> ReaderExecutedAsync(
DbCommand command,
CommandExecutedEventData eventData,
DbDataReader result,
CancellationToken cancellationToken = default)
{
if (eventData.CommandSource == CommandSource.LinqQuery && eventData.Duration.TotalMilliseconds > _slowQueryThresholdInMilliseconds)
{
LogSlowQuery(command, eventData);
}
return base.ReaderExecutedAsync(command, eventData, result, cancellationToken);
}
private void LogSlowQuery(DbCommand command, CommandExecutedEventData eventData)
{
logger.LogWarning("Slow query detected : ({Duration} ms): {CommandText}",
eventData.Duration.TotalMilliseconds, command.CommandText);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment