Created
January 11, 2024 22:04
-
-
Save MeladKamari/ef8e9058a0ada915029ab253055354ad to your computer and use it in GitHub Desktop.
SlowQueryInterceptor
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
| 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