Skip to content

Instantly share code, notes, and snippets.

@MeladKamari
Created January 11, 2024 22:04
Show Gist options
  • Select an option

  • Save MeladKamari/ef8e9058a0ada915029ab253055354ad to your computer and use it in GitHub Desktop.

Select an option

Save MeladKamari/ef8e9058a0ada915029ab253055354ad to your computer and use it in GitHub Desktop.
SlowQueryInterceptor
public class SlowQueryInterceptor : IDbCommandInterceptor
{
private const int SlowQueryThreshold = 200; // milliSecond
public DbDataReader ReaderExecuted(
DbCommand command,
CommandExecutedEventData eventData,
DbDataReader result)
{
if (!(eventData.Duration.TotalMilliseconds > SlowQueryThreshold)) return result;
var factory = eventData.Context!.Database.GetService<ILoggerFactory>();
var logger = factory.CreateLogger<SlowQueryInterceptor>();
logger.LogWarning("Slow Query ({Duration} ms): {CommandText}",
eventData.Duration.TotalMilliseconds.ToString(CultureInfo.CurrentCulture),
command.CommandText);
return result;
}
}
builder.Services.AddDbContext<ApplicationDbContextCore>((provider, dbContextOptionsBuilder) =>
{
dbContextOptionsBuilder.UseSqlServer(builder.Configuration.GetConnectionString("ApplicationConnection"))
.AddInterceptors(new SlowQueryInterceptor());
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment