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>
This commit is contained in:
@@ -1,5 +1,7 @@
|
||||
using System.Diagnostics;
|
||||
using HrynCo.NotificationService.DAL.Abstract;
|
||||
using MediatR;
|
||||
using Microsoft.Extensions.Logging;
|
||||
|
||||
namespace HrynCo.NotificationService.Services.Behaviors;
|
||||
|
||||
@@ -7,19 +9,36 @@ public class TransactionBehavior<TRequest, TResponse> : IPipelineBehavior<TReque
|
||||
where TRequest : notnull
|
||||
{
|
||||
private readonly IUnitOfWork _unitOfWork;
|
||||
private readonly ILogger<TransactionBehavior<TRequest, TResponse>> _logger;
|
||||
|
||||
public TransactionBehavior(IUnitOfWork unitOfWork)
|
||||
public TransactionBehavior(IUnitOfWork unitOfWork, ILogger<TransactionBehavior<TRequest, TResponse>> logger)
|
||||
{
|
||||
_unitOfWork = unitOfWork;
|
||||
_logger = logger;
|
||||
}
|
||||
|
||||
public Task<TResponse> Handle(TRequest request, RequestHandlerDelegate<TResponse> next, CancellationToken cancellationToken)
|
||||
public async Task<TResponse> Handle(TRequest request, RequestHandlerDelegate<TResponse> next, CancellationToken cancellationToken)
|
||||
{
|
||||
return _unitOfWork.ExecuteInTransactionAsync(async () =>
|
||||
string handlerName = typeof(TRequest).Name;
|
||||
_logger.LogDebug("Handling {Handler}", handlerName);
|
||||
|
||||
Stopwatch sw = Stopwatch.StartNew();
|
||||
try
|
||||
{
|
||||
TResponse result = await next();
|
||||
await _unitOfWork.SaveChangesAsync(cancellationToken);
|
||||
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;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user