Last active
January 2, 2025 19:22
-
-
Save davepcallan/91d4cc9922b12e6f5c537effcdc173c2 to your computer and use it in GitHub Desktop.
Finding slow queries with Entity Framework Interceptors
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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