Skip to content

Commit 6ffc055

Browse files
committed
add func: UseReuestResponseLog middleware 🎨
1 parent b5b7935 commit 6ffc055

7 files changed

Lines changed: 191 additions & 12 deletions

File tree

Blog.Core.Common/LogHelper/LogLock.cs

Lines changed: 24 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -35,7 +35,7 @@ public static void OutSql2Log(string filename, string[] dataParas)
3535
string logFilePath = path + $@"\{filename}.log";
3636

3737
var now = DateTime.Now;
38-
var logContent = string.Format(
38+
var logContent = (
3939
"--------------------------------\r\n" +
4040
DateTime.Now + "|\r\n" +
4141
String.Join("\r\n", dataParas) + "\r\n"
@@ -44,8 +44,9 @@ public static void OutSql2Log(string filename, string[] dataParas)
4444
File.AppendAllText(logFilePath, logContent);
4545
WritedCount++;
4646
}
47-
catch (Exception)
47+
catch (Exception e)
4848
{
49+
Console.Write(e.Message);
4950
FailedCount++;
5051
}
5152
finally
@@ -94,6 +95,7 @@ public static List<LogInfo> GetLogData()
9495
List<LogInfo> aopLogs = new List<LogInfo>();
9596
List<LogInfo> excLogs = new List<LogInfo>();
9697
List<LogInfo> sqlLogs = new List<LogInfo>();
98+
List<LogInfo> reqresLogs = new List<LogInfo>();
9799
try
98100
{
99101
aopLogs = ReadLog(Path.Combine(Directory.GetCurrentDirectory(), "Log", "AOPLog.log"), Encoding.UTF8)
@@ -145,6 +147,22 @@ public static List<LogInfo> GetLogData()
145147
{
146148
}
147149

150+
try
151+
{
152+
reqresLogs = ReadLog(Path.Combine(Directory.GetCurrentDirectory(), "Log", "RequestResponseLog.log"), Encoding.UTF8)
153+
.Split("--------------------------------")
154+
.Where(d => !string.IsNullOrEmpty(d) && d != "\n" && d != "\r\n")
155+
.Select(d => new LogInfo
156+
{
157+
Datetime = d.Split("|")[0].ObjToDate(),
158+
Content = d.Split("|")[1]?.Replace("\r\n", "<br>"),
159+
LogColor = "ReqRes",
160+
}).ToList();
161+
}
162+
catch (Exception)
163+
{
164+
}
165+
148166
if (excLogs != null)
149167
{
150168
aopLogs.AddRange(excLogs);
@@ -153,6 +171,10 @@ public static List<LogInfo> GetLogData()
153171
{
154172
aopLogs.AddRange(sqlLogs);
155173
}
174+
if (reqresLogs != null)
175+
{
176+
aopLogs.AddRange(reqresLogs);
177+
}
156178
aopLogs = aopLogs.OrderByDescending(d => d.Import).ThenByDescending(d => d.Datetime).Take(100).ToList();
157179

158180
return aopLogs;

Blog.Core/AuthHelper/OverWrite/JwtTokenAuth.cs

Lines changed: 1 addition & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -88,13 +88,6 @@ public Task Invoke(HttpContext httpContext)
8888
}
8989

9090
}
91-
92-
public static class MiddlewareHelpers
93-
{
94-
public static IApplicationBuilder UseJwtTokenAuth(this IApplicationBuilder app)
95-
{
96-
return app.UseMiddleware<JwtTokenAuth>();
97-
}
98-
}
91+
9992
}
10093

Blog.Core/Blog.Core.xml

Lines changed: 17 additions & 0 deletions
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.
Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,17 @@
1+
using Blog.Core.AuthHelper;
2+
using Microsoft.AspNetCore.Builder;
3+
4+
namespace Blog.Core.Middlewares
5+
{
6+
public static class MiddlewareHelpers
7+
{
8+
public static IApplicationBuilder UseJwtTokenAuth(this IApplicationBuilder app)
9+
{
10+
return app.UseMiddleware<JwtTokenAuth>();
11+
}
12+
public static IApplicationBuilder UseReuestResponseLog(this IApplicationBuilder app)
13+
{
14+
return app.UseMiddleware<RequRespLogMildd>();
15+
}
16+
}
17+
}
Lines changed: 117 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,117 @@
1+
using Microsoft.AspNetCore.Http;
2+
using System;
3+
using System.Collections.Generic;
4+
using System.Linq;
5+
using System.Security.Claims;
6+
using System.Threading.Tasks;
7+
using Blog.Core.AuthHelper.OverWrite;
8+
using Microsoft.AspNetCore.Builder;
9+
using System.IO;
10+
using Blog.Core.Common.LogHelper;
11+
using StackExchange.Profiling;
12+
13+
namespace Blog.Core.Middlewares
14+
{
15+
/// <summary>
16+
/// 中间件
17+
/// 记录请求和响应数据
18+
/// </summary>
19+
public class RequRespLogMildd
20+
{
21+
/// <summary>
22+
///
23+
/// </summary>
24+
private readonly RequestDelegate _next;
25+
/// <summary>
26+
///
27+
/// </summary>
28+
/// <param name="next"></param>
29+
public RequRespLogMildd(RequestDelegate next)
30+
{
31+
_next = next;
32+
}
33+
34+
35+
36+
public async Task InvokeAsync(HttpContext context)
37+
{
38+
// 过滤,只有接口
39+
if (context.Request.Path.Value.Contains("api"))
40+
{
41+
context.Request.EnableBuffering();
42+
Stream originalBody = context.Response.Body;
43+
44+
try
45+
{
46+
// 存储请求数据
47+
RequestDataLog(context.Request);
48+
49+
using (var ms = new MemoryStream())
50+
{
51+
context.Response.Body = ms;
52+
53+
await _next(context);
54+
55+
// 存储响应数据
56+
ResponseDataLog(context.Response, ms);
57+
58+
ms.Position = 0;
59+
await ms.CopyToAsync(originalBody);
60+
}
61+
}
62+
catch (Exception ex)
63+
{
64+
// 记录异常
65+
//ErrorLogData(context.Response, ex);
66+
}
67+
finally
68+
{
69+
context.Response.Body = originalBody;
70+
}
71+
}
72+
else
73+
{
74+
await _next(context);
75+
}
76+
}
77+
78+
private void RequestDataLog(HttpRequest request)
79+
{
80+
var sr = new StreamReader(request.Body);
81+
82+
var content = $" QueryData:{request.Path + request.QueryString}\r\n BodyData:{sr.ReadToEnd()}";
83+
84+
if (!string.IsNullOrEmpty(content))
85+
{
86+
Parallel.For(0, 1, e =>
87+
{
88+
LogLock log = new LogLock();
89+
LogLock.OutSql2Log("RequestResponseLog", new string[] { "Request Data:", content });
90+
91+
});
92+
93+
request.Body.Position = 0;
94+
}
95+
96+
}
97+
98+
99+
private void ResponseDataLog(HttpResponse response, MemoryStream ms)
100+
{
101+
ms.Position = 0;
102+
var ResponseBody = new StreamReader(ms).ReadToEnd();
103+
104+
if (!string.IsNullOrEmpty(ResponseBody))
105+
{
106+
Parallel.For(0, 1, e =>
107+
{
108+
LogLock log = new LogLock();
109+
LogLock.OutSql2Log("RequestResponseLog", new string[] { "Response Data:", ResponseBody });
110+
111+
});
112+
}
113+
}
114+
115+
}
116+
}
117+

Blog.Core/Startup.cs

Lines changed: 12 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -18,6 +18,7 @@
1818
using Blog.Core.Filter;
1919
using Blog.Core.Hubs;
2020
using Blog.Core.Log;
21+
using Blog.Core.Middlewares;
2122
using Blog.Core.Model;
2223
using log4net;
2324
using log4net.Config;
@@ -429,11 +430,18 @@ public IServiceProvider ConfigureServices(IServiceCollection services)
429430
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
430431
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
431432
{
433+
if (Appsettings.app("AppSettings", "Middleware_RequestResponse", "Enabled").ObjToBool())
434+
{
435+
app.UseReuestResponseLog();//记录请求与返回数据
436+
}
437+
438+
432439
#region Environment
433440
if (env.IsDevelopment())
434441
{
435442
// 在开发环境中,使用异常页面,这样可以暴露错误堆栈信息,所以不要放在生产环境。
436443
app.UseDeveloperExceptionPage();
444+
437445
}
438446
else
439447
{
@@ -445,7 +453,6 @@ public void Configure(IApplicationBuilder app, IHostingEnvironment env)
445453
}
446454
#endregion
447455

448-
449456
#region Swagger
450457
app.UseSwagger();
451458
app.UseSwaggerUI(c =>
@@ -487,15 +494,18 @@ public void Configure(IApplicationBuilder app, IHostingEnvironment env)
487494

488495
#endregion
489496

497+
490498
// 跳转https
491-
app.UseHttpsRedirection();
499+
//app.UseHttpsRedirection();
492500
// 使用静态文件
493501
app.UseStaticFiles();
494502
// 使用cookie
495503
app.UseCookiePolicy();
496504
// 返回错误码
497505
app.UseStatusCodePages();//把错误码返回前台,比如是404
498506

507+
508+
499509
app.UseMvc();
500510

501511

Blog.Core/appsettings.json

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -21,6 +21,9 @@
2121
"Enabled": false,
2222
"ConnectionString": "127.0.0.1:6319"
2323
},
24+
"Middleware_RequestResponse": {
25+
"Enabled": true
26+
},
2427
"MemoryCachingAOP": {
2528
"Enabled": true
2629
},

0 commit comments

Comments
 (0)