using MediatR; using Microsoft.Extensions.Logging; using System.Diagnostics; namespace DocumentOperator.Application.Common.Behaviors; /// /// MediatR Pipeline Behavior that logs requests and tracks performance /// Executes AFTER ValidationBehavior, BEFORE Handler /// public class LoggingBehavior(ILogger> Logger) : IPipelineBehavior where TRequest : IRequest { public async Task Handle( TRequest request, RequestHandlerDelegate next, CancellationToken cancellationToken) { var requestName = typeof(TRequest).Name; // Performance Tracking var stopwatch = Stopwatch.StartNew(); try { // Handler ausführen var response = await next(cancellationToken); stopwatch.Stop(); // Request Success Logger.LogInformation( "Handled {RequestName} in {ElapsedMs}ms", requestName, stopwatch.ElapsedMilliseconds ); return response; } catch (Exception ex) { stopwatch.Stop(); // Request Failed Logger.LogError( ex, "Error handling {RequestName} after {ElapsedMs}ms: {ErrorMessage}", requestName, stopwatch.ElapsedMilliseconds, ex.Message ); throw; // Exception weiterwerfen (wird von Exception Middleware gefangen) } } }