54 lines
2.0 KiB
C#
54 lines
2.0 KiB
C#
using System.Data.Common;
|
|
using Microsoft.EntityFrameworkCore.Diagnostics;
|
|
using Microsoft.Extensions.Logging;
|
|
|
|
namespace Budget.Infrastructure.Data;
|
|
|
|
public class SlowQueryInterceptor(ILogger<SlowQueryInterceptor> logger) : DbCommandInterceptor
|
|
{
|
|
private static readonly TimeSpan Threshold = TimeSpan.FromMilliseconds(500);
|
|
|
|
public override DbDataReader ReaderExecuted(DbCommand command, CommandExecutedEventData eventData, DbDataReader result)
|
|
{
|
|
LogIfSlow(command, eventData.Duration);
|
|
return result;
|
|
}
|
|
|
|
public override ValueTask<DbDataReader> ReaderExecutedAsync(DbCommand command, CommandExecutedEventData eventData, DbDataReader result, CancellationToken cancellationToken = default)
|
|
{
|
|
LogIfSlow(command, eventData.Duration);
|
|
return new ValueTask<DbDataReader>(result);
|
|
}
|
|
|
|
public override int NonQueryExecuted(DbCommand command, CommandExecutedEventData eventData, int result)
|
|
{
|
|
LogIfSlow(command, eventData.Duration);
|
|
return result;
|
|
}
|
|
|
|
public override ValueTask<int> NonQueryExecutedAsync(DbCommand command, CommandExecutedEventData eventData, int result, CancellationToken cancellationToken = default)
|
|
{
|
|
LogIfSlow(command, eventData.Duration);
|
|
return new ValueTask<int>(result);
|
|
}
|
|
|
|
public override object? ScalarExecuted(DbCommand command, CommandExecutedEventData eventData, object? result)
|
|
{
|
|
LogIfSlow(command, eventData.Duration);
|
|
return result;
|
|
}
|
|
|
|
public override ValueTask<object?> ScalarExecutedAsync(DbCommand command, CommandExecutedEventData eventData, object? result, CancellationToken cancellationToken = default)
|
|
{
|
|
LogIfSlow(command, eventData.Duration);
|
|
return new ValueTask<object?>(result);
|
|
}
|
|
|
|
private void LogIfSlow(DbCommand command, TimeSpan duration)
|
|
{
|
|
if (duration >= Threshold)
|
|
logger.LogWarning("Slow query ({Duration}ms): {CommandText}",
|
|
(long)duration.TotalMilliseconds, command.CommandText);
|
|
}
|
|
}
|