首页 > Web开发 > 详细

.net core 中间件 记录日志

时间:2021-02-08 22:33:39      阅读:31      评论:0      收藏:0      [点我收藏+]
 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     }

 

.net core 中间件 记录日志

原文:https://www.cnblogs.com/liyixi/p/14389781.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!