Advertisement
Guest User

loggingBehavior

a guest
Feb 20th, 2020
155
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 1.50 KB | None | 0 0
  1. using System;
  2. using System.Threading;
  3. using System.Threading.Tasks;
  4. using MediatR;
  5. using Serilog;
  6. using Serilog.Core;
  7.  
  8. namespace UserService.Infrastructure
  9. {
  10.     /// <summary>
  11.     /// Logging behavior for mediatr
  12.     /// </summary>
  13.     /// <typeparam name="TRequest"></typeparam>
  14.     /// <typeparam name="TResponse"></typeparam>
  15.     public class LoggingBehavior<TRequest, TResponse> : IPipelineBehavior<TRequest, TResponse>
  16.     {
  17.         private readonly ILogger _logger = Log.Logger.ForContext(Constants.SourceContextPropertyName, "Mediatr");
  18.        
  19.         /// <inheritdoc />
  20.         public async Task<TResponse> Handle(TRequest request, CancellationToken cancellationToken, RequestHandlerDelegate<TResponse> next)
  21.         {
  22.             var requestName = typeof(TRequest).Name;
  23.            
  24.             _logger
  25.                 .ForContext("Request", request, true)
  26.                 .Information("Handling {RequestType:l}", requestName);
  27.  
  28.             TResponse response;
  29.             try
  30.             {
  31.                 response = await next();
  32.             }
  33.             catch (Exception ex)
  34.             {
  35.                 _logger
  36.                     .ForContext("Error", ex, true)
  37.                     .Information("Failed {RequestType:l}", requestName);
  38.                 throw;
  39.             }
  40.  
  41.             _logger
  42.                 .ForContext("Response", response, true)
  43.                 .Information("Handled {RequestType:l}", requestName);
  44.  
  45.             return response;
  46.         }
  47.     }
  48. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement