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

时间:2018-07-12 12:28:41

标签: .net asp.net-web-api logging asp.net-core

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

我在配置中使用ILogger:

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

根据要求,我会看到日志:

  

信息:Microsoft.AspNetCore.Mvc.Internal.ControllerActionInvoker [1]         执行动作方法ActivationService.Controllers.ActivationController.Post   (ActivationService)带参数   (ActivationService.Contracts.ActivationRequest)-验证状态:   有效

  

执行的动作方法   ActivationService.Controllers.ActivationController.Post   (ActivationService),返回结果   Microsoft.AspNetCore.Mvc.ObjectResult在174605.9201毫秒内。

是否可以配置asp.net以记录响应和请求的痕迹 body

1 个答案:

答案 0 :(得分:2)

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

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>();
}