Files
hrynco-notification-service/HrynCo.NotificationService.Services/Behaviors/TransactionBehavior.cs
T
Anatolii Grynchuk 101bb908bd feat: add Serilog with Console and Seq sinks, log TransactionBehavior
- Add Serilog.AspNetCore + Sinks.Console + Sinks.Seq to Api
- Add Serilog.Extensions.Hosting + Sinks.Console + Sinks.Seq to Worker
- Add Microsoft.Extensions.Logging.Abstractions to Services
- TransactionBehavior logs handler name, elapsed time, and errors

Ref: IT-628

Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
2026-05-02 00:21:25 +03:00

44 lines
1.5 KiB
C#

using System.Diagnostics;
using HrynCo.NotificationService.DAL.Abstract;
using MediatR;
using Microsoft.Extensions.Logging;
namespace HrynCo.NotificationService.Services.Behaviors;
public class TransactionBehavior<TRequest, TResponse> : IPipelineBehavior<TRequest, TResponse>
where TRequest : notnull
{
private readonly IUnitOfWork _unitOfWork;
private readonly ILogger<TransactionBehavior<TRequest, TResponse>> _logger;
public TransactionBehavior(IUnitOfWork unitOfWork, ILogger<TransactionBehavior<TRequest, TResponse>> logger)
{
_unitOfWork = unitOfWork;
_logger = logger;
}
public async Task<TResponse> Handle(TRequest request, RequestHandlerDelegate<TResponse> next, CancellationToken cancellationToken)
{
string handlerName = typeof(TRequest).Name;
_logger.LogDebug("Handling {Handler}", handlerName);
Stopwatch sw = Stopwatch.StartNew();
try
{
TResponse result = await _unitOfWork.ExecuteInTransactionAsync(async () =>
{
TResponse response = await next();
await _unitOfWork.SaveChangesAsync(cancellationToken);
return response;
});
_logger.LogDebug("Handled {Handler} in {ElapsedMs}ms", handlerName, sw.ElapsedMilliseconds);
return result;
}
catch (Exception ex)
{
_logger.LogError(ex, "Handler {Handler} failed after {ElapsedMs}ms", handlerName, sw.ElapsedMilliseconds);
throw;
}
}
}