From be1190971319d9c6f7ee553de9b27885e2c90e8b Mon Sep 17 00:00:00 2001 From: lg <999544862qq.com> Date: 星期三, 14 八月 2024 15:48:45 +0800 Subject: [PATCH] 陆工,增加异常过滤 --- MESApplication/bin/Debug/net8.0/MESApplication.pdb | 0 MESApplication/Startup.cs | 13 ++ MESApplication/bin/Debug/net8.0/MESApplication.exe | 0 MESApplication/Controllers/Base/DemoController.cs | 2 MESApplication/Filter/ErrorLog.cs | 70 ++++++++++++++ MESApplication/bin/Debug/net8.0/MES.Service.pdb | 0 MESApplication/bin/Debug/net8.0/MESApplication.dll | 0 MESApplication/Filter/ActionFilter.cs | 160 ++++++++++++++++++++++++++++++++ MES.Service/bin/Debug/net8.0/MES.Service.dll | 0 MESApplication/bin/Debug/net8.0/MES.Service.dll | 0 MES.Service/bin/Debug/net8.0/MES.Service.pdb | 0 11 files changed, 244 insertions(+), 1 deletions(-) diff --git a/MES.Service/bin/Debug/net8.0/MES.Service.dll b/MES.Service/bin/Debug/net8.0/MES.Service.dll index 59e24d7..c4ce8db 100644 --- a/MES.Service/bin/Debug/net8.0/MES.Service.dll +++ b/MES.Service/bin/Debug/net8.0/MES.Service.dll Binary files differ diff --git a/MES.Service/bin/Debug/net8.0/MES.Service.pdb b/MES.Service/bin/Debug/net8.0/MES.Service.pdb index f33968d..a83db2b 100644 --- a/MES.Service/bin/Debug/net8.0/MES.Service.pdb +++ b/MES.Service/bin/Debug/net8.0/MES.Service.pdb Binary files differ diff --git a/MESApplication/Controllers/Base/DemoController.cs b/MESApplication/Controllers/Base/DemoController.cs index ce0eaba..0a28eae 100644 --- a/MESApplication/Controllers/Base/DemoController.cs +++ b/MESApplication/Controllers/Base/DemoController.cs @@ -3,7 +3,6 @@ using MES.Service.util; using Microsoft.AspNetCore.Mvc; using Newtonsoft.Json.Linq; - namespace MESApplication.Controllers.Base; [Route("api/[controller]")] @@ -28,6 +27,7 @@ } catch (Exception ex) { + throw ex; return ResponseResult.ResponseError(ex); } } diff --git a/MESApplication/Filter/ActionFilter.cs b/MESApplication/Filter/ActionFilter.cs new file mode 100644 index 0000000..222c03f --- /dev/null +++ b/MESApplication/Filter/ActionFilter.cs @@ -0,0 +1,160 @@ +锘縰sing Microsoft.AspNetCore.Mvc; +using Microsoft.AspNetCore.Mvc.Controllers; +using Microsoft.AspNetCore.Mvc.Filters; +using Newtonsoft.Json; +using System.Diagnostics; +using System.Text; + +namespace MESApplication +{ + /// <summary> + /// 鏂规硶杩囨护鍣� + /// </summary> + public class ActionFilter : IActionFilter + { + /// <summary> + /// 鐩戞帶鏃ュ織 + /// </summary> + public static ILogger LoggerMonitor { get; set; } + + /// <summary> + /// 閿欒鏃ュ織 + /// </summary> + public static ILogger LoggerError { get; set; } + + private Stopwatch _stopwatch; + + /// <summary> + /// 鍒涘缓璇锋眰鏃ュ織鏂囨湰 + /// </summary> + /// <param name="method"></param> + /// <param name="controllerName"></param> + /// <param name="actionName"></param> + /// <param name="actionArgs"></param> + /// <returns></returns> + private static string CreateRequestLogText(string method, string controllerName, string actionName, string requestHead, string requestBody) + { + StringBuilder sb = new StringBuilder(); + sb.Append($"{DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss:fff")} 璇锋眰{method}/{controllerName}/{actionName}鎺ュ彛锛岃姹侶ead锛歿requestHead}\n"); + sb.Append($"{DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss:fff")} 璇锋眰{method}/{controllerName}/{actionName}鎺ュ彛锛岃姹侭ody锛歿requestBody}\n"); + return sb.ToString(); + } + + /// <summary> + /// 鍒涘缓鍝嶅簲鏃ュ織鏂囨湰 + /// </summary> + /// <param name="method"></param> + /// <param name="controllerName"></param> + /// <param name="actionName"></param> + /// <param name="result"></param> + /// <returns></returns> + private static string CreateResponseLogText(string method, string controllerName, string actionName, object result) + { + StringBuilder sb = new StringBuilder(); + sb.Append($"{DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss:fff")} 瀹屾垚璇锋眰{method}/{controllerName}/{actionName}鎺ュ彛锛岃繑鍥炵粨鏋滐細"); + if (result != null) + { + sb.Append($"{JsonConvert.SerializeObject(result)}"); + } + else + { + sb.Append($"鏃�"); + } + return sb.ToString(); + } + + + /// <summary> + /// 鏂规硶鎵ц鍓� + /// </summary> + /// <param name="context"></param> + /// <exception cref="NotImplementedException"></exception> + public async void OnActionExecuting(ActionExecutingContext context) + { + // ErrorLog.Write("=================================================================================================================================="); + _stopwatch = new Stopwatch(); + _stopwatch.Start(); + //throw new NotImplementedException(); + if (LoggerMonitor != null) + { + //璁板綍璇锋眰鍙傛暟鏃ュ織 + ControllerActionDescriptor desc = context.ActionDescriptor as ControllerActionDescriptor; + if (desc != null) + { + Dictionary<string, object> headers = new Dictionary<string, object>(); + var requestHeaders = context.HttpContext.Request.Headers; + + // 璁块棶璇锋眰涓殑 header 淇℃伅 + foreach (var header in requestHeaders) + { + headers.Add(header.Key, header.Value); + } + var requestHead = JsonConvert.SerializeObject(headers); + + Dictionary<string, object> bodys = new Dictionary<string, object>(); + var actionArguments = context.ActionArguments; + // 璁块棶璇锋眰涓殑鍙傛暟 + foreach (var argument in actionArguments) + { + //dic.Add(argument.Key, argument.Value); + var parameter = JsonConvert.DeserializeObject<Dictionary<string, object>>(argument.Value.ToString()); + foreach (var item in parameter) + { + bodys.Add(item.Key, item.Value); + } + } + var requestBody = JsonConvert.SerializeObject(bodys); + + var logText = CreateRequestLogText(context.HttpContext.Request.Method, desc.ControllerName, desc.ActionName, requestHead, requestBody); + //LoggerMonitor.LogDebug(logText); + //ErrorLog.Write(logText); + } + } + + + } + + public void OnActionExecuted(ActionExecutedContext context) + { + //throw new NotImplementedException(); + _stopwatch.Stop(); + long elaspsedMillisedconds = _stopwatch.ElapsedMilliseconds; + string msg = ""; + //string msg = $"{DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss:fff")} 鎺ュ彛鎵ц鏃堕棿锛歿elaspsedMillisedconds}姣"; + //ErrorLog.Write(msg); + + if (context.Exception != null) + { + // 璁板綍寮傚父鏃ュ織 + if (LoggerError != null) + { + LoggerError.LogError(context.Exception, context.Exception.Message); + + ErrorLog.Write($@"{DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss:fff")} 鎺ュ彛寮傚父锛歿JsonConvert.SerializeObject(context.Exception)}"); + ErrorLog.Write($@"{DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss:fff")} 寮傚父鎻愮ず淇℃伅锛歿JsonConvert.SerializeObject(context.Exception.Message)}"); + ErrorLog.Write("=================================================================================================================================="); + } + } + + if (LoggerMonitor != null) + { + // 璁板綍璇锋眰缁撴灉鏃ュ織 + ControllerActionDescriptor desc = context.ActionDescriptor as ControllerActionDescriptor; + if (desc != null) + { + ObjectResult rst = context.Result as ObjectResult; + object rstValue = rst != null ? rst.Value : null; + var logText = CreateResponseLogText( + context.HttpContext.Request.Method, + desc.ControllerName, + desc.ActionName, + rstValue); + LoggerMonitor.LogDebug(logText); + ErrorLog.Write(logText); + } + } + // ErrorLog.Write(msg); + // ErrorLog.Write("=================================================================================================================================="); + } + } +} diff --git a/MESApplication/Filter/ErrorLog.cs b/MESApplication/Filter/ErrorLog.cs new file mode 100644 index 0000000..26fe4f6 --- /dev/null +++ b/MESApplication/Filter/ErrorLog.cs @@ -0,0 +1,70 @@ +锘縩amespace MESApplication +{ + public class ErrorLog + { + + private static string DirectoryPath = AppDomain.CurrentDomain.BaseDirectory; + + /// <summary> + /// 鍐欏叆鎿嶄綔鏃ュ織鍒版枃浠朵腑 + /// </summary> + /// <param name="moduleName">妯″潡鍚嶅瓧</param> + /// <param name="message">閿欒鏂囨湰淇℃伅</param> + /// <param name="ex">寮傚父</param> + public static void Write(string moduleName, string message, Exception ex) + { + //string directoryPath = $@"C:\鑷崇畝绉戞妧\MyDemoData\.NetCore鎺ュ彛杩囨护鍣ㄩ」鐩甛FilterText\FilterText\Logger\{DateTime.Now.ToString("yyyyMMdd")}"; // 鐩爣鐩綍璺緞 + string directoryPath = $@"{DirectoryPath}{"log"}"; // 鐩爣鐩綍璺緞 + + if (!Directory.Exists(directoryPath)) + { + // 濡傛灉鐩綍涓嶅瓨鍦紝鍒欐柊寤烘枃浠跺す + Directory.CreateDirectory(directoryPath); + } + + string filePath = directoryPath + $@"\{DateTime.Now.ToString("yyyyMMddHH")}.log"; // 鐩爣鏂囦欢璺緞 + + if (!File.Exists(filePath)) + { + // 濡傛灉鏂囦欢涓嶅瓨鍦紝鍒欏垱寤烘枃浠� + using (File.Create(filePath)) + { + //Console.WriteLine("鏂囦欢宸插垱寤�"); + } + } + LogToFile(filePath, message); + } + + /// <summary> + /// 鍐欏叆鎿嶄綔鏃ュ織鍒版枃浠朵腑 + /// </summary> + /// <param name="moduleName">妯″潡鍚嶅瓧</param> + /// <param name="ex">寮傚父</param> + public static void Write(string moduleName, Exception ex) + { + Write(moduleName, moduleName, ex); + } + + /// <summary> + /// 鍐欏叆杩囩▼鏁版嵁鎴栬鏄庡埌鏂囦欢涓紝浠ヤ究璺熻釜 + /// </summary> + /// <param name="moduleName">妯″潡鍚嶅瓧</param> + /// <param name="ex">寮傚父</param> + public static void Write(string message) + { + Write(String.Empty, message, null); + } + + /// <summary> + /// 鏂囨湰鍐欏叆 + /// </summary> + /// <param name="logMessage"></param> + private static void LogToFile(string logFilePath, string logMessage) + { + using (StreamWriter sw = File.AppendText(logFilePath)) + { + sw.WriteLine($"{logMessage}"); + } + } + } +} diff --git a/MESApplication/Startup.cs b/MESApplication/Startup.cs index f506f0e..17e9bf6 100644 --- a/MESApplication/Startup.cs +++ b/MESApplication/Startup.cs @@ -66,6 +66,14 @@ "OPTIONS") ); }); + + #region 鎺ュ彛琛屽姩杩囨护鍣� + services.AddControllers(options => { + options.Filters.Add(new ActionFilter()); + }); + var serviceProvider = services.BuildServiceProvider(); + ActionFilter.LoggerError = serviceProvider.GetRequiredService<ILogger<ActionFilter>>(); + #endregion } // This method gets called by the runtime. Use this method to configure the HTTP request pipeline. @@ -92,5 +100,10 @@ app.UseAuthorization(); app.UseEndpoints(endpoints => { endpoints.MapControllers(); }); + + ////////////////////////// + + /////////////////////////// + } } \ No newline at end of file diff --git a/MESApplication/bin/Debug/net8.0/MES.Service.dll b/MESApplication/bin/Debug/net8.0/MES.Service.dll index 59e24d7..c4ce8db 100644 --- a/MESApplication/bin/Debug/net8.0/MES.Service.dll +++ b/MESApplication/bin/Debug/net8.0/MES.Service.dll Binary files differ diff --git a/MESApplication/bin/Debug/net8.0/MES.Service.pdb b/MESApplication/bin/Debug/net8.0/MES.Service.pdb index f33968d..a83db2b 100644 --- a/MESApplication/bin/Debug/net8.0/MES.Service.pdb +++ b/MESApplication/bin/Debug/net8.0/MES.Service.pdb Binary files differ diff --git a/MESApplication/bin/Debug/net8.0/MESApplication.dll b/MESApplication/bin/Debug/net8.0/MESApplication.dll index ec28191..f07464e 100644 --- a/MESApplication/bin/Debug/net8.0/MESApplication.dll +++ b/MESApplication/bin/Debug/net8.0/MESApplication.dll Binary files differ diff --git a/MESApplication/bin/Debug/net8.0/MESApplication.exe b/MESApplication/bin/Debug/net8.0/MESApplication.exe index 673b7af..3e84f41 100644 --- a/MESApplication/bin/Debug/net8.0/MESApplication.exe +++ b/MESApplication/bin/Debug/net8.0/MESApplication.exe Binary files differ diff --git a/MESApplication/bin/Debug/net8.0/MESApplication.pdb b/MESApplication/bin/Debug/net8.0/MESApplication.pdb index cd92d34..f89865e 100644 --- a/MESApplication/bin/Debug/net8.0/MESApplication.pdb +++ b/MESApplication/bin/Debug/net8.0/MESApplication.pdb Binary files differ -- Gitblit v1.9.3