Original code from X @Dave_DotNet modified to use Serilog for when a slow query is detected
Created
August 14, 2025 13:52
-
-
Save karenpayneoregon/4458622ab55979fded368d3f786febe1 to your computer and use it in GitHub Desktop.
EF Core slow query Interceptor
This file contains hidden or 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 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(); | |
| } | |
| } |
This file contains hidden or 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 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