Response body for request/response Logging

前端 未结 3 714
花落未央
花落未央 2021-02-09 04:55

I\'m trying to write a Owin midleware component that would LOG every incoming request and response to the database.

Here\'s how far I managed to get.

I got stu

3条回答
  •  忘了有多久
    2021-02-09 05:36

    I've solved the problem by applying an action attribute writing the request body to OWIN environment dictionary. After that, the logging middleware can access it by a key.

    public class LogResponseBodyInterceptorAttribute : ActionFilterAttribute
    {
        public override async Task OnActionExecutedAsync(HttpActionExecutedContext actionExecutedContext, CancellationToken cancellationToken)
        {
            if (actionExecutedContext?.Response?.Content is ObjectContent)
            {
                actionExecutedContext.Request.GetOwinContext().Environment["log-responseBody"] =
                    await actionExecutedContext.Response.Content.ReadAsStringAsync();
            }
        }
    }
    

    And then in the middleware:

    public class RequestLoggingMiddleware
    {
        ...
        private void LogResponse(IOwinContext owinContext)
        {
            var message = new StringBuilder()
                .AppendLine($"{owinContext.Response.StatusCode}")
                .AppendLine(string.Join(Environment.NewLine, owinContext.Response.Headers.Select(x => $"{x.Key}: {string.Join("; ", x.Value)}")));
    
            if (owinContext.Environment.ContainsKey("log-responseBody"))
            {
                var responseBody = (string)owinContext.Environment["log-responseBody"];
                message.AppendLine()
                    .AppendLine(responseBody);
            }
    
            var logEvent = new LogEventInfo
            {
                Level = LogLevel.Trace,
                Properties =
                {
                    {"correlationId", owinContext.Environment["correlation-id"]},
                    {"entryType", "Response"}
                },
                Message = message.ToString()
            };
    
            _logger.Log(logEvent);
        }
    }
    

提交回复
热议问题