Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- using System;
- using System.Threading;
- using System.Threading.Tasks;
- using MediatR;
- using Serilog;
- using Serilog.Core;
- namespace UserService.Infrastructure
- {
- /// <summary>
- /// Logging behavior for mediatr
- /// </summary>
- /// <typeparam name="TRequest"></typeparam>
- /// <typeparam name="TResponse"></typeparam>
- public class LoggingBehavior<TRequest, TResponse> : IPipelineBehavior<TRequest, TResponse>
- {
- private readonly ILogger _logger = Log.Logger.ForContext(Constants.SourceContextPropertyName, "Mediatr");
- /// <inheritdoc />
- public async Task<TResponse> Handle(TRequest request, CancellationToken cancellationToken, RequestHandlerDelegate<TResponse> next)
- {
- var requestName = typeof(TRequest).Name;
- _logger
- .ForContext("Request", request, true)
- .Information("Handling {RequestType:l}", requestName);
- TResponse response;
- try
- {
- response = await next();
- }
- catch (Exception ex)
- {
- _logger
- .ForContext("Error", ex, true)
- .Information("Failed {RequestType:l}", requestName);
- throw;
- }
- _logger
- .ForContext("Response", response, true)
- .Information("Handled {RequestType:l}", requestName);
- return response;
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement