| | 1 | | using Domain.Common; |
| | 2 | | using MediatR; |
| | 3 | | using Microsoft.Extensions.Logging; |
| | 4 | | using Serilog.Context; |
| | 5 | |
|
| | 6 | | namespace Application.Pipelines; |
| | 7 | |
|
| | 8 | | internal sealed class QueryLoggingBehavior<TRequest, TResponse> |
| | 9 | | : IPipelineBehavior<TRequest, TResponse> |
| | 10 | | where TRequest : class |
| | 11 | | where TResponse : Result |
| | 12 | | { |
| | 13 | | private readonly ILogger<QueryLoggingBehavior<TRequest, TResponse>> _logger; |
| | 14 | |
|
| 2 | 15 | | public QueryLoggingBehavior(ILogger<QueryLoggingBehavior<TRequest, TResponse>> logger) |
| 2 | 16 | | { |
| 2 | 17 | | _logger = logger; |
| 2 | 18 | | } |
| | 19 | |
|
| | 20 | | public async Task<TResponse> Handle( |
| | 21 | | TRequest request, |
| | 22 | | RequestHandlerDelegate<TResponse> next, |
| | 23 | | CancellationToken cancellationToken) |
| 2 | 24 | | { |
| 2 | 25 | | string requestName = typeof(TRequest).Name; |
| | 26 | |
|
| 2 | 27 | | _logger.LogInformation("Processing request {RequestName}", requestName); |
| | 28 | |
|
| 2 | 29 | | TResponse result = await next(); |
| | 30 | |
|
| 2 | 31 | | if (result.IsSuccess) |
| 1 | 32 | | { |
| 1 | 33 | | _logger.LogInformation("Completed request {RequestName}", requestName); |
| 1 | 34 | | } |
| | 35 | | else |
| 1 | 36 | | { |
| 1 | 37 | | using (LogContext.PushProperty("Error", result.Error, true)) |
| 1 | 38 | | { |
| 1 | 39 | | _logger.LogError("Completed request {RequestName} with error", requestName); |
| 1 | 40 | | } |
| 1 | 41 | | } |
| | 42 | |
|
| 2 | 43 | | return result; |
| 2 | 44 | | } |
| | 45 | | } |