Rename folder from Shogi.Sockets to Shogi.Api
This commit is contained in:
50
Shogi.Api/Extensions/LogMiddleware.cs
Normal file
50
Shogi.Api/Extensions/LogMiddleware.cs
Normal file
@@ -0,0 +1,50 @@
|
||||
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;
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user