Skip to content

Instantly share code, notes, and snippets.

@elanderson
Created February 7, 2017 12:46
Show Gist options
  • Star 24 You must be signed in to star a gist
  • Fork 6 You must be signed in to fork a gist
  • Save elanderson/c50b2107de8ee2ed856353dfed9168a2 to your computer and use it in GitHub Desktop.
Save elanderson/c50b2107de8ee2ed856353dfed9168a2 to your computer and use it in GitHub Desktop.
Request Response Logging Middleware for ASP.NET Core
public class RequestResponseLoggingMiddleware
{
private readonly RequestDelegate _next;
private readonly ILogger _logger;
public RequestResponseLoggingMiddleware(RequestDelegate next,
ILoggerFactory loggerFactory)
{
_next = next;
_logger = loggerFactory
.CreateLogger<RequestResponseLoggingMiddleware>();
}
public async Task Invoke(HttpContext context)
{
_logger.LogInformation(await FormatRequest(context.Request));
var originalBodyStream = context.Response.Body;
using (var responseBody = new MemoryStream())
{
context.Response.Body = responseBody;
await _next(context);
_logger.LogInformation(await FormatResponse(context.Response));
await responseBody.CopyToAsync(originalBodyStream);
}
}
private async Task<string> FormatRequest(HttpRequest request)
{
var body = request.Body;
request.EnableRewind();
var buffer = new byte[Convert.ToInt32(request.ContentLength)];
await request.Body.ReadAsync(buffer, 0, buffer.Length);
var bodyAsText = Encoding.UTF8.GetString(buffer);
request.Body = body;
return $"{request.Scheme} {request.Host}{request.Path} {request.QueryString} {bodyAsText}";
}
private async Task<string> FormatResponse(HttpResponse response)
{
response.Body.Seek(0, SeekOrigin.Begin);
var text = await new StreamReader(response.Body).ReadToEndAsync();
response.Body.Seek(0, SeekOrigin.Begin);
return $"Response {text}";
}
}
public static class RequestResponseLoggingMiddlewareExtensions
{
public static IApplicationBuilder UseRequestResponseLogging(this IApplicationBuilder builder)
{
return builder.UseMiddleware<RequestResponseLoggingMiddleware>();
}
}
@ghasemi1994
Copy link

@petret
thank uuuuuuuuuuuuu woooooooooooow!!!!!!!!

@unseensenpai
Copy link

unseensenpai commented Sep 21, 2023

I struggelered a lot with body request null.

Tried on .NET 8 and working fine. Added some cool details and json limit (100 char) for log file size.

Request Response Logging in .Net 8
You can find all files here for implementation

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment