51 lines
1.1 KiB
C#
51 lines
1.1 KiB
C#
using Microsoft.AspNetCore.Builder;
|
|
using Microsoft.AspNetCore.Http;
|
|
using Microsoft.Extensions.Logging;
|
|
using System.IO;
|
|
using System.Text;
|
|
using System.Threading.Tasks;
|
|
|
|
namespace Shogi.Api.Extensions
|
|
{
|
|
public class LogMiddleware
|
|
{
|
|
private readonly RequestDelegate next;
|
|
private readonly ILogger logger;
|
|
|
|
|
|
public LogMiddleware(RequestDelegate next, ILoggerFactory factory)
|
|
{
|
|
this.next = next;
|
|
logger = factory.CreateLogger<LogMiddleware>();
|
|
}
|
|
|
|
public async Task Invoke(HttpContext context)
|
|
{
|
|
try
|
|
{
|
|
await next(context);
|
|
}
|
|
finally
|
|
{
|
|
using var stream = new MemoryStream();
|
|
context.Request?.Body.CopyToAsync(stream);
|
|
|
|
logger.LogInformation("Request {method} {url} => {statusCode} \n Body: {body}",
|
|
context.Request?.Method,
|
|
context.Request?.Path.Value,
|
|
context.Response?.StatusCode,
|
|
Encoding.UTF8.GetString(stream.ToArray()));
|
|
}
|
|
}
|
|
}
|
|
|
|
public static class IApplicationBuilderExtensions
|
|
{
|
|
public static IApplicationBuilder UseRequestResponseLogging(this IApplicationBuilder builder)
|
|
{
|
|
builder.UseMiddleware<LogMiddleware>();
|
|
return builder;
|
|
}
|
|
}
|
|
}
|