using System.Diagnostics;
using MediatR;
using Microsoft.Extensions.Logging;
namespace MyNewProjectName.Application.Behaviors;
///
/// Logging behavior for MediatR pipeline
///
public class LoggingBehavior : IPipelineBehavior
where TRequest : notnull
{
private readonly ILogger> _logger;
public LoggingBehavior(ILogger> logger)
{
_logger = logger;
}
public async Task Handle(TRequest request, RequestHandlerDelegate next, CancellationToken cancellationToken)
{
var requestName = typeof(TRequest).Name;
_logger.LogInformation("Handling {RequestName}", requestName);
var stopwatch = Stopwatch.StartNew();
try
{
var response = await next();
stopwatch.Stop();
_logger.LogInformation("Handled {RequestName} in {ElapsedMilliseconds}ms",
requestName, stopwatch.ElapsedMilliseconds);
return response;
}
catch (Exception ex)
{
stopwatch.Stop();
_logger.LogError(ex, "Error handling {RequestName} after {ElapsedMilliseconds}ms",
requestName, stopwatch.ElapsedMilliseconds);
throw;
}
}
}