diff --git "a/.Net6\347\211\210\346\234\254/VOL.Core/Extensions/StringExtension.cs" "b/.Net6\347\211\210\346\234\254/VOL.Core/Extensions/StringExtension.cs" index 8be7827bd..4a259f031 100644 --- "a/.Net6\347\211\210\346\234\254/VOL.Core/Extensions/StringExtension.cs" +++ "b/.Net6\347\211\210\346\234\254/VOL.Core/Extensions/StringExtension.cs" @@ -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) + "..."; + } } } diff --git "a/.Net6\347\211\210\346\234\254/VOL.Core/Middleware/ExceptionHandlerMiddleWare.cs" "b/.Net6\347\211\210\346\234\254/VOL.Core/Middleware/ExceptionHandlerMiddleWare.cs" index fa31cc305..1a7419173 100644 --- "a/.Net6\347\211\210\346\234\254/VOL.Core/Middleware/ExceptionHandlerMiddleWare.cs" +++ "b/.Net6\347\211\210\346\234\254/VOL.Core/Middleware/ExceptionHandlerMiddleWare.cs" @@ -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; @@ -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()放在 app.UseRouting()后才可以在await next(context);前执行 - Endpoint endpoint = context.Features.Get()?.Endpoint; - if (endpoint != null && endpoint is RouteEndpoint routeEndpoint) - { - ActionLog log = endpoint.Metadata.GetMetadata(); - 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); } } } diff --git "a/.Net6\347\211\210\346\234\254/VOL.WebApi/Startup.cs" "b/.Net6\347\211\210\346\234\254/VOL.WebApi/Startup.cs" index 94cd1b97f..0a11102d6 100644 --- "a/.Net6\347\211\210\346\234\254/VOL.WebApi/Startup.cs" +++ "b/.Net6\347\211\210\346\234\254/VOL.WebApi/Startup.cs" @@ -216,12 +216,12 @@ public void Configure(IApplicationBuilder app, IWebHostEnvironment env) { app.UseQuartz(env); } - app.UseMiddleware(); app.UseDefaultFiles(); app.UseStaticFiles().UseStaticFiles(new StaticFileOptions { ServeUnknownFileTypes = true }); + app.UseMiddleware(); app.Use(HttpRequestMiddleware.Context); //2021.06.27增加创建默认upload文件夹 diff --git a/Net6.SqlSugar/VOL.Core/Extensions/StringExtension.cs b/Net6.SqlSugar/VOL.Core/Extensions/StringExtension.cs index 8be7827bd..1972903df 100644 --- a/Net6.SqlSugar/VOL.Core/Extensions/StringExtension.cs +++ b/Net6.SqlSugar/VOL.Core/Extensions/StringExtension.cs @@ -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) + "..."; + } + } } diff --git a/Net6.SqlSugar/VOL.Core/Middleware/ExceptionHandlerMiddleWare.cs b/Net6.SqlSugar/VOL.Core/Middleware/ExceptionHandlerMiddleWare.cs index bc949f142..1a7419173 100644 --- a/Net6.SqlSugar/VOL.Core/Middleware/ExceptionHandlerMiddleWare.cs +++ b/Net6.SqlSugar/VOL.Core/Middleware/ExceptionHandlerMiddleWare.cs @@ -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; @@ -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()放在 app.UseRouting()后才可以在await next(context);前执行 - Endpoint endpoint = context.Features.Get()?.Endpoint; - if (endpoint != null && endpoint is RouteEndpoint routeEndpoint) - { - ActionLog log = endpoint.Metadata.GetMetadata(); - 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); } } } diff --git a/Net6.SqlSugar/VOL.Core/Services/Logger.cs b/Net6.SqlSugar/VOL.Core/Services/Logger.cs index 898a30c09..9bf70bdd1 100644 --- a/Net6.SqlSugar/VOL.Core/Services/Logger.cs +++ b/Net6.SqlSugar/VOL.Core/Services/Logger.cs @@ -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; } diff --git a/Net6.SqlSugar/VOL.WebApi/Startup.cs b/Net6.SqlSugar/VOL.WebApi/Startup.cs index d6d20b109..cbda5c381 100644 --- a/Net6.SqlSugar/VOL.WebApi/Startup.cs +++ b/Net6.SqlSugar/VOL.WebApi/Startup.cs @@ -220,12 +220,12 @@ public void Configure(IApplicationBuilder app, IWebHostEnvironment env) { app.UseQuartz(env); } - app.UseMiddleware(); app.UseDefaultFiles(); app.UseStaticFiles().UseStaticFiles(new StaticFileOptions { ServeUnknownFileTypes = true }); + app.UseMiddleware(); app.Use(HttpRequestMiddleware.Context); //2021.06.27增加创建默认upload文件夹 diff --git "a/\345\274\200\345\217\221\347\211\210dev/Net6\345\274\200\345\217\221\347\211\210/VOL.Core/Middleware/ExceptionHandlerMiddleWare.cs" "b/\345\274\200\345\217\221\347\211\210dev/Net6\345\274\200\345\217\221\347\211\210/VOL.Core/Middleware/ExceptionHandlerMiddleWare.cs" index fa31cc305..1a7419173 100644 --- "a/\345\274\200\345\217\221\347\211\210dev/Net6\345\274\200\345\217\221\347\211\210/VOL.Core/Middleware/ExceptionHandlerMiddleWare.cs" +++ "b/\345\274\200\345\217\221\347\211\210dev/Net6\345\274\200\345\217\221\347\211\210/VOL.Core/Middleware/ExceptionHandlerMiddleWare.cs" @@ -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; @@ -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()放在 app.UseRouting()后才可以在await next(context);前执行 - Endpoint endpoint = context.Features.Get()?.Endpoint; - if (endpoint != null && endpoint is RouteEndpoint routeEndpoint) - { - ActionLog log = endpoint.Metadata.GetMetadata(); - 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); } } }