Skip to content

Instantly share code, notes, and snippets.

@umayeras
Created November 12, 2021 11:44
Show Gist options
  • Save umayeras/899f6a45eef1403f31d380d9dc573711 to your computer and use it in GitHub Desktop.
Save umayeras/899f6a45eef1403f31d380d9dc573711 to your computer and use it in GitHub Desktop.
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