gpt4 book ai didi

.net - 配置 .net 核心日志记录以记录请求和响应

转载 作者:行者123 更新时间:2023-12-01 01:15:33 36 4
gpt4 key购买 nike

我正在开发asp .net core 2.1 WEB-API 应用程序。

我将 ILogger 与配置一起使用:

"Logging": {
"LogLevel": {
"Default": "Debug",
"System": "Information",
"Microsoft": "Information"
}

并应要求我看到日志:

info: Microsoft.AspNetCore.Mvc.Internal.ControllerActionInvoker[1] Executing action method ActivationService.Controllers.ActivationController.Post (ActivationService) with arguments (ActivationService.Contracts.ActivationRequest) - Validation state: Valid





Executed action method ActivationService.Controllers.ActivationController.Post (ActivationService), returned result Microsoft.AspNetCore.Mvc.ObjectResult in 174605.9201ms.



有没有办法配置 asp.net 以跟踪日志 正文 响应和请求?

最佳答案

是的,您可以实现日志记录中间件:

public class RequestResponseLoggingMiddleware
{
private readonly RequestDelegate next;
private readonly ILogger logger;

public RequestResponseLoggingMiddleware(RequestDelegate next, ILoggerFactory loggerFactory)
{
this.next = next;
logger = loggerFactory.CreateLogger<RequestResponseLoggingMiddleware>();
}

public async Task Invoke(HttpContext context)
{
context.Request.EnableRewind();

var buffer = new byte[Convert.ToInt32(context.Request.ContentLength)];
await context.Request.Body.ReadAsync(buffer, 0, buffer.Length);
var requestBody = Encoding.UTF8.GetString(buffer);
context.Request.Body.Seek(0, SeekOrigin.Begin);

logger.LogInformation(requestBody);

var originalBodyStream = context.Response.Body;

using (var responseBody = new MemoryStream())
{
context.Response.Body = responseBody;

await next(context);

context.Response.Body.Seek(0, SeekOrigin.Begin);
var response = await new StreamReader(context.Response.Body).ReadToEndAsync();
context.Response.Body.Seek(0, SeekOrigin.Begin);

logger.LogInformation(response);
await responseBody.CopyToAsync(originalBodyStream);
}
}
}

然后在 Configure 方法中将其添加到 application Builder 中:
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
....
app.UseMiddleware<RequestResponseLoggingMiddleware>();
}

关于.net - 配置 .net 核心日志记录以记录请求和响应,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51305718/

36 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com