1 /// <summary> 2 /// 记录请求和返回报文 3 /// </summary> 4 public class RequestResponseLoggingMiddleware 5 { 6 private readonly RequestDelegate _next; 7 private readonly Stopwatch _stopwatch; 8 9 /// <summary> 10 /// 11 /// </summary> 12 /// <param name="next"></param> 13 public RequestResponseLoggingMiddleware(RequestDelegate next) 14 { 15 _next = next; 16 _stopwatch = new Stopwatch(); 17 } 18 19 public async Task Invoke(HttpContext context) 20 { 21 try 22 { 23 _stopwatch.Restart(); 24 25 #region request 26 27 var request = context.Request; 28 Log.Info("request.url:" + request.Path.ToString()); 29 Log.Info("request.method:" + request.Method); 30 Log.Info("request.headers:" + request.Headers.ToDictionary(x => x.Key, v => string.Join(";", v.Value.ToList())).ToJson()); 31 Log.Info("request.executeStartTime:" + DateTimeOffset.Now.ToString("yyyy-MM-dd HH:mm:ss.fff")); 32 33 var body = ""; 34 if (request.Method.ToLower().Equals("post")) 35 { 36 request.EnableBuffering(); 37 38 var stream = request.Body; 39 if (request.ContentLength != null) 40 { 41 var buffer = new byte[request.ContentLength.Value]; 42 await stream.ReadAsync(buffer, 0, buffer.Length); 43 body = Encoding.UTF8.GetString(buffer); 44 } 45 46 request.Body.Position = 0; 47 } 48 else if (request.Method.ToLower().Equals("get")) 49 { 50 body = request.QueryString.Value; 51 } 52 Log.Info("request.body:" + body); 53 #endregion 54 55 #region response 56 var originalResponseStream = context.Response.Body; 57 58 await using var ms = new MemoryStream(); 59 context.Response.Body = ms; 60 61 await _next(context); 62 63 var downstreamRequest = context.Items.DownstreamRequest(); 64 if (downstreamRequest != null) 65 { 66 Log.Info($"response.Method:{downstreamRequest.Method}"); 67 Log.Info($"response uri:{downstreamRequest}"); 68 Log.Info("response.headers:" + downstreamRequest.Headers.ToDictionary(x => x.Key, v => string.Join(";", v.Value.ToList())).ToJson()); 69 } 70 71 context.Response.Body.Position = 0; 72 using var reader = new StreamReader(context.Response.Body); 73 Log.Info($"response.body:{reader.ReadToEnd()}"); 74 context.Response.Body.Position = 0; 75 await ms.CopyToAsync(originalResponseStream); 76 context.Response.Body = originalResponseStream; 77 Log.Info("response.executeEndTime:" + DateTimeOffset.Now.ToString("yyyy-MM-dd HH:mm:ss.fff")); 78 #endregion 79 80 // 响应完成记录时间和存入日志 81 context.Response.OnCompleted(() => 82 { 83 _stopwatch.Stop(); 84 Log.Info($"stopwatch:{_stopwatch.ElapsedMilliseconds} ms"); 85 return Task.CompletedTask; 86 }); 87 } 88 catch (Exception e) 89 { 90 Log.Error("RequestResponseLoggingMiddleware invoke error", e); 91 throw; 92 } 93 } 94 }