lg
2024-08-14 be1190971319d9c6f7ee553de9b27885e2c90e8b
陆工,增加异常过滤
已添加2个文件
已修改9个文件
245 ■■■■■ 文件已修改
MES.Service/bin/Debug/net8.0/MES.Service.dll 补丁 | 查看 | 原始文档 | blame | 历史
MES.Service/bin/Debug/net8.0/MES.Service.pdb 补丁 | 查看 | 原始文档 | blame | 历史
MESApplication/Controllers/Base/DemoController.cs 2 ●●● 补丁 | 查看 | 原始文档 | blame | 历史
MESApplication/Filter/ActionFilter.cs 160 ●●●●● 补丁 | 查看 | 原始文档 | blame | 历史
MESApplication/Filter/ErrorLog.cs 70 ●●●●● 补丁 | 查看 | 原始文档 | blame | 历史
MESApplication/Startup.cs 13 ●●●●● 补丁 | 查看 | 原始文档 | blame | 历史
MESApplication/bin/Debug/net8.0/MES.Service.dll 补丁 | 查看 | 原始文档 | blame | 历史
MESApplication/bin/Debug/net8.0/MES.Service.pdb 补丁 | 查看 | 原始文档 | blame | 历史
MESApplication/bin/Debug/net8.0/MESApplication.dll 补丁 | 查看 | 原始文档 | blame | 历史
MESApplication/bin/Debug/net8.0/MESApplication.exe 补丁 | 查看 | 原始文档 | blame | 历史
MESApplication/bin/Debug/net8.0/MESApplication.pdb 补丁 | 查看 | 原始文档 | blame | 历史
MES.Service/bin/Debug/net8.0/MES.Service.dll
Binary files differ
MES.Service/bin/Debug/net8.0/MES.Service.pdb
Binary files differ
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);
        }
    }
MESApplication/Filter/ActionFilter.cs
¶Ô±ÈÐÂÎļþ
@@ -0,0 +1,160 @@
using 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}接口,请求Head:{requestHead}\n");
            sb.Append($"{DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss:fff")} è¯·æ±‚{method}/{controllerName}/{actionName}接口,请求Body:{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("==================================================================================================================================");
        }
    }
}
MESApplication/Filter/ErrorLog.cs
¶Ô±ÈÐÂÎļþ
@@ -0,0 +1,70 @@
namespace 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}");
            }
        }
    }
}
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(); });
        //////////////////////////
        ///////////////////////////
    }
}
MESApplication/bin/Debug/net8.0/MES.Service.dll
Binary files differ
MESApplication/bin/Debug/net8.0/MES.Service.pdb
Binary files differ
MESApplication/bin/Debug/net8.0/MESApplication.dll
Binary files differ
MESApplication/bin/Debug/net8.0/MESApplication.exe
Binary files differ
MESApplication/bin/Debug/net8.0/MESApplication.pdb
Binary files differ