Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

重写了请求参数日志的记录,可以正常记录请求和返回的参数 #353

Open
wants to merge 6 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
7 changes: 6 additions & 1 deletion .Net6版本/VOL.Core/Extensions/StringExtension.cs
Original file line number Diff line number Diff line change
Expand Up @@ -577,6 +577,11 @@ public static string GenerateRandomNumber(this int length)
}
return newRandom.ToString();
}


public static string TruncateToLength(this string str, int maxLength = 1000)
{
if (string.IsNullOrEmpty(str)) return str;
return str.Length <= maxLength ? str : str.Substring(0, maxLength) + "...";
}
}
}
87 changes: 53 additions & 34 deletions .Net6版本/VOL.Core/Middleware/ExceptionHandlerMiddleWare.cs
Original file line number Diff line number Diff line change
@@ -1,22 +1,18 @@
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Http.Features;
using Microsoft.AspNetCore.Routing;
using Microsoft.Extensions.Hosting;
using System;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using VOL.Core.Const;
using VOL.Core.EFDbContext;
using VOL.Core.Enums;
using VOL.Core.Extensions;
using VOL.Core.ManageUser;
using VOL.Core.Services;

namespace VOL.Core.Middleware
{

public class ExceptionHandlerMiddleWare
{
private readonly RequestDelegate next;
Expand All @@ -27,42 +23,65 @@ public ExceptionHandlerMiddleWare(RequestDelegate next)

public async Task Invoke(HttpContext context)
{
try
context.Request.EnableBuffering();

var requestBodyStream = new MemoryStream();
await context.Request.Body.CopyToAsync(requestBodyStream);
requestBodyStream.Seek(0, SeekOrigin.Begin);

var requestBodyText = new StreamReader(requestBodyStream).ReadToEnd();

// Get the URL parameters
var urlParameters = context.Request.Query;
if (urlParameters.Count > 0)
{
context.Request.EnableBuffering();
(context.RequestServices.GetService(typeof(ActionObserver)) as ActionObserver).RequestDate = DateTime.Now;
await next(context);
//app.UseMiddleware<ExceptionHandlerMiddleWare>()放在 app.UseRouting()后才可以在await next(context);前执行
Endpoint endpoint = context.Features.Get<IEndpointFeature>()?.Endpoint;
if (endpoint != null && endpoint is RouteEndpoint routeEndpoint)
{
ActionLog log = endpoint.Metadata.GetMetadata<ActionLog>();
if (log != null && log.Write)
{
Logger.Add(log?.LogType, null, null, null, status: LoggerStatus.Info);
}
}
else
{
Logger.Info(LoggerType.Info);
}
var formattedParameters = string.Join("&", urlParameters.Select(x => $"{x.Key}={x.Value}"));
requestBodyText = "URL 参数: " + formattedParameters + Environment.NewLine + requestBodyText;
}
catch (Exception exception)

requestBodyStream.Seek(0, SeekOrigin.Begin);
context.Request.Body = requestBodyStream;

// Create a new memory stream
var originalBodyStream = context.Response.Body;
using (var responseBody = new MemoryStream())
{
var env = context.RequestServices.GetService(typeof(IWebHostEnvironment)) as IWebHostEnvironment;
string message = exception.Message + exception.StackTrace + exception.InnerException;
Logger.Error(LoggerType.Exception, message);
if (!env.IsDevelopment())
try
{
message = "服务器处理异常";
// Replace the context response body with our memory stream
context.Response.Body = responseBody;

(context.RequestServices.GetService(typeof(ActionObserver)) as ActionObserver).RequestDate = DateTime.Now;
// Continue down the Middleware pipeline
await next(context);

// Copy the contents of the new memory stream (which contains the response) to the original stream
responseBody.Seek(0, SeekOrigin.Begin);
var responseBodyText = new StreamReader(responseBody).ReadToEnd();

Logger.Info(LoggerType.System, requestBodyText.TruncateToLength(), responseBodyText.TruncateToLength());


responseBody.Seek(0, SeekOrigin.Begin);
await responseBody.CopyToAsync(originalBodyStream);
}
else
catch (Exception exception)
{
Console.WriteLine($"服务器处理出现异常:{message}");
var env = context.RequestServices.GetService(typeof(IWebHostEnvironment)) as IWebHostEnvironment;
string message = exception.Message + exception.InnerException;
Logger.Error(LoggerType.Exception, requestBodyText.TruncateToLength(), "", message);
if (!env.IsDevelopment())
{
message = "服务器处理异常";
}
else
{
Console.WriteLine($"服务器处理出现异常:{message}");
}
context.Response.StatusCode = 500;
context.Response.ContentType = ApplicationContentType.JSON;
await context.Response.WriteAsync(new { message, status = false }.Serialize(), Encoding.UTF8);
}
context.Response.StatusCode = 500;
context.Response.ContentType = ApplicationContentType.JSON;
await context.Response.WriteAsync(new { message, status = false }.Serialize(), Encoding.UTF8);
}
}
}
Expand Down
2 changes: 1 addition & 1 deletion .Net6版本/VOL.WebApi/Startup.cs
Original file line number Diff line number Diff line change
Expand Up @@ -216,12 +216,12 @@ public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
app.UseQuartz(env);
}
app.UseMiddleware<ExceptionHandlerMiddleWare>();
app.UseDefaultFiles();
app.UseStaticFiles().UseStaticFiles(new StaticFileOptions
{
ServeUnknownFileTypes = true
});
app.UseMiddleware<ExceptionHandlerMiddleWare>();
app.Use(HttpRequestMiddleware.Context);

//2021.06.27增加创建默认upload文件夹
Expand Down
6 changes: 6 additions & 0 deletions Net6.SqlSugar/VOL.Core/Extensions/StringExtension.cs
Original file line number Diff line number Diff line change
Expand Up @@ -578,5 +578,11 @@ public static string GenerateRandomNumber(this int length)
return newRandom.ToString();
}

public static string TruncateToLength(this string str, int maxLength = 1000)
{
if (string.IsNullOrEmpty(str)) return str;
return str.Length <= maxLength ? str : str.Substring(0, maxLength) + "...";
}

}
}
86 changes: 53 additions & 33 deletions Net6.SqlSugar/VOL.Core/Middleware/ExceptionHandlerMiddleWare.cs
Original file line number Diff line number Diff line change
@@ -1,21 +1,18 @@
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Http.Features;
using Microsoft.AspNetCore.Routing;
using Microsoft.Extensions.Hosting;
using System;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using VOL.Core.Const;
using VOL.Core.Enums;
using VOL.Core.Extensions;
using VOL.Core.ManageUser;
using VOL.Core.Services;

namespace VOL.Core.Middleware
{

public class ExceptionHandlerMiddleWare
{
private readonly RequestDelegate next;
Expand All @@ -26,42 +23,65 @@ public ExceptionHandlerMiddleWare(RequestDelegate next)

public async Task Invoke(HttpContext context)
{
try
context.Request.EnableBuffering();

var requestBodyStream = new MemoryStream();
await context.Request.Body.CopyToAsync(requestBodyStream);
requestBodyStream.Seek(0, SeekOrigin.Begin);

var requestBodyText = new StreamReader(requestBodyStream).ReadToEnd();

// Get the URL parameters
var urlParameters = context.Request.Query;
if (urlParameters.Count > 0)
{
context.Request.EnableBuffering();
(context.RequestServices.GetService(typeof(ActionObserver)) as ActionObserver).RequestDate = DateTime.Now;
await next(context);
//app.UseMiddleware<ExceptionHandlerMiddleWare>()放在 app.UseRouting()后才可以在await next(context);前执行
Endpoint endpoint = context.Features.Get<IEndpointFeature>()?.Endpoint;
if (endpoint != null && endpoint is RouteEndpoint routeEndpoint)
{
ActionLog log = endpoint.Metadata.GetMetadata<ActionLog>();
if (log != null && log.Write)
{
Logger.Add(log?.LogType, null, null, null, status: LoggerStatus.Info);
}
}
else
{
Logger.Info(LoggerType.Info);
}
var formattedParameters = string.Join("&", urlParameters.Select(x => $"{x.Key}={x.Value}"));
requestBodyText = "URL 参数: " + formattedParameters + Environment.NewLine + requestBodyText;
}
catch (Exception exception)

requestBodyStream.Seek(0, SeekOrigin.Begin);
context.Request.Body = requestBodyStream;

// Create a new memory stream
var originalBodyStream = context.Response.Body;
using (var responseBody = new MemoryStream())
{
var env = context.RequestServices.GetService(typeof(IWebHostEnvironment)) as IWebHostEnvironment;
string message = exception.Message + exception.InnerException;
Logger.Error(LoggerType.Exception, message);
if (!env.IsDevelopment())
try
{
message = "服务器处理异常";
// Replace the context response body with our memory stream
context.Response.Body = responseBody;

(context.RequestServices.GetService(typeof(ActionObserver)) as ActionObserver).RequestDate = DateTime.Now;
// Continue down the Middleware pipeline
await next(context);

// Copy the contents of the new memory stream (which contains the response) to the original stream
responseBody.Seek(0, SeekOrigin.Begin);
var responseBodyText = new StreamReader(responseBody).ReadToEnd();

Logger.Info(LoggerType.System, requestBodyText.TruncateToLength(), responseBodyText.TruncateToLength());


responseBody.Seek(0, SeekOrigin.Begin);
await responseBody.CopyToAsync(originalBodyStream);
}
else
catch (Exception exception)
{
Console.WriteLine($"服务器处理出现异常:{message}");
var env = context.RequestServices.GetService(typeof(IWebHostEnvironment)) as IWebHostEnvironment;
string message = exception.Message + exception.InnerException;
Logger.Error(LoggerType.Exception, requestBodyText.TruncateToLength(), "", message);
if (!env.IsDevelopment())
{
message = "服务器处理异常";
}
else
{
Console.WriteLine($"服务器处理出现异常:{message}");
}
context.Response.StatusCode = 500;
context.Response.ContentType = ApplicationContentType.JSON;
await context.Response.WriteAsync(new { message, status = false }.Serialize(), Encoding.UTF8);
}
context.Response.StatusCode = 500;
context.Response.ContentType = ApplicationContentType.JSON;
await context.Response.WriteAsync(new { message, status = false }.Serialize(), Encoding.UTF8);
}
}
}
Expand Down
4 changes: 4 additions & 0 deletions Net6.SqlSugar/VOL.Core/Services/Logger.cs
Original file line number Diff line number Diff line change
Expand Up @@ -168,6 +168,10 @@ private static void Start()
if (loggerQueueData.Count() > 0 && list.Count < 500)
{
loggerQueueData.TryDequeue(out Sys_Log log);
if (log.EndDate != null && log.BeginDate != null)
{
log.ElapsedTime = (int)(((DateTime)log.EndDate - (DateTime)log.BeginDate).TotalMilliseconds);
}
list.Add(log);
continue;
}
Expand Down
2 changes: 1 addition & 1 deletion Net6.SqlSugar/VOL.WebApi/Startup.cs
Original file line number Diff line number Diff line change
Expand Up @@ -220,12 +220,12 @@ public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
app.UseQuartz(env);
}
app.UseMiddleware<ExceptionHandlerMiddleWare>();
app.UseDefaultFiles();
app.UseStaticFiles().UseStaticFiles(new StaticFileOptions
{
ServeUnknownFileTypes = true
});
app.UseMiddleware<ExceptionHandlerMiddleWare>();
app.Use(HttpRequestMiddleware.Context);

//2021.06.27增加创建默认upload文件夹
Expand Down
Loading