private async Task <WebRestLog> LogRequest(HttpRequest request, WebRestLog log) { var body = request.Body; request.EnableRewind(); var buffer = new byte[Convert.ToInt32(request.ContentLength)]; await request.Body.ReadAsync(buffer, 0, buffer.Length); var bodyAsText = Encoding.UTF8.GetString(buffer); request.Body = body; log.Scheme = request.Scheme; log.Host = request.Host.ToString(); log.Path = request.Path; log.QueryString = request.QueryString.ToString(); log.RequestBody = bodyAsText; log.ClientIp = request.HttpContext.Connection.RemoteIpAddress.ToString(); log.HttpMethod = request.Method; log.Start = DateTime.UtcNow; return(log); }
public async Task Invoke(HttpContext context) { WebRestLog log = new WebRestLog() { TraceId = context.TraceIdentifier }; try { log = await LogRequest(context.Request, log); } catch (Exception e) { Loki.ExceptionWarning("Error in Loki Middleware logging Request", e); } var originalBodyStream = context.Response.Body; using (var responseBody = new MemoryStream()) { context.Response.Body = responseBody; await _next(context); await LogResponse(context.Response, log); await responseBody.CopyToAsync(originalBodyStream); } }
private async Task LogResponse(HttpResponse response, WebRestLog log) { response.Body.Seek(0, SeekOrigin.Begin); string text = await new StreamReader(response.Body).ReadToEndAsync(); response.Body.Seek(0, SeekOrigin.Begin); log.StatusCode = response.StatusCode; log.End = DateTime.UtcNow; log.ResponseBody = text; }