You cannot select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
56 lines
1.9 KiB
C#
56 lines
1.9 KiB
C#
namespace Ds.Module.MediatR
|
|
{
|
|
/// <summary>
|
|
///
|
|
/// </summary>
|
|
/// <typeparam name="TRequest"></typeparam>
|
|
/// <typeparam name="TResponse"></typeparam>
|
|
public class PerformanceMonitorBehavior<TRequest, TResponse> : IPipelineBehavior<TRequest, TResponse>
|
|
{
|
|
private ILogger<PerformanceMonitorBehavior<TRequest, TResponse>> _logger;
|
|
|
|
public PerformanceMonitorBehavior(ILogger<PerformanceMonitorBehavior<TRequest, TResponse>> logger)
|
|
{
|
|
_logger = logger ?? throw new ArgumentNullException(nameof(logger));
|
|
}
|
|
|
|
public async Task<TResponse> Handle(TRequest request, RequestHandlerDelegate<TResponse> next, CancellationToken cancellationToken)
|
|
{
|
|
// 只有在调试模式下才记录,这样就不会在生产环境中加重负担
|
|
#if DEBUG
|
|
var typeName = typeof(TRequest).Name;
|
|
|
|
LogPrePerformanceData(typeName);
|
|
|
|
Stopwatch stopwatch = Stopwatch.StartNew();
|
|
try
|
|
{
|
|
return await next();
|
|
}
|
|
finally
|
|
{
|
|
stopwatch.Stop();
|
|
LogPostPerformanceData(typeName, stopwatch);
|
|
}
|
|
#else
|
|
return await next();
|
|
#endif
|
|
}
|
|
|
|
private void LogPrePerformanceData(string typeName)
|
|
{
|
|
_logger.LogInformation("----- Handling command {CommandType}", typeName);
|
|
}
|
|
|
|
private void LogPostPerformanceData(string typeName, Stopwatch stopwatch)
|
|
{
|
|
_logger.LogInformation("----- Done handling command {CommandType} (ElapsedMilliseconds = {ElapsedMilliseconds})", typeName, stopwatch.ElapsedMilliseconds);
|
|
}
|
|
|
|
//使用时需要在Startup.cs中注册
|
|
//services.AddTransient(typeof(IPipelineBehavior<,>), typeof(ValidationBehavior<,>));
|
|
//services.AddTransient(typeof(IPipelineBehavior<,>), typeof(PerformanceMonitorBehavior<,>));
|
|
|
|
}
|
|
}
|