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