Created
November 12, 2021 11:44
-
-
Save umayeras/899f6a45eef1403f31d380d9dc573711 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public class LoggingBehavior<TRequest, TResponse> : IPipelineBehavior<TRequest, TResponse> | |
{ | |
private readonly ILogger<TRequest> logger; | |
public LoggingBehavior(ILogger<TRequest> logger) | |
{ | |
this.logger = logger; | |
} | |
public async Task<TResponse> Handle(TRequest request, CancellationToken cancellationToken, RequestHandlerDelegate<TResponse> next) | |
{ | |
var requestNameWithGuid = $"{request.GetType().Name} [{Guid.NewGuid().ToString()}]"; | |
logger.LogInformation($"[START] {requestNameWithGuid}"); | |
var stopwatch = Stopwatch.StartNew(); | |
try | |
{ | |
LogRequestWithProps(request, requestNameWithGuid); | |
return await next(); | |
} | |
finally | |
{ | |
stopwatch.Stop(); | |
logger.LogInformation($"[END] {requestNameWithGuid}; Execution time={stopwatch.ElapsedMilliseconds}ms"); | |
} | |
} | |
private void LogRequestWithProps(TRequest request, string requestNameWithGuid) | |
{ | |
try | |
{ | |
logger.LogInformation($"[PROPS] {requestNameWithGuid} {JsonSerializer.Serialize(request)}"); | |
} | |
catch (NotSupportedException) | |
{ | |
logger.LogInformation($"[Serialization ERROR] {requestNameWithGuid} Could not serialize the request."); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment