From 46e98339480d853fc78a014c34d7ff9fcaf13890 Mon Sep 17 00:00:00 2001
From: dengjunjie <dengjunjie@hnkhzn.com>
Date: 星期四, 05 十二月 2024 14:09:02 +0800
Subject: [PATCH] 产线协议

---
 项目代码/WMS/WIDESEA_WMSServer/WIDESEA_Core/AOP/LogAOP.cs |  328 ++++++++++++++++++++++++++++++++++++++++++++++++++++++
 1 files changed, 328 insertions(+), 0 deletions(-)

diff --git "a/\351\241\271\347\233\256\344\273\243\347\240\201/WMS/WIDESEA_WMSServer/WIDESEA_Core/AOP/LogAOP.cs" "b/\351\241\271\347\233\256\344\273\243\347\240\201/WMS/WIDESEA_WMSServer/WIDESEA_Core/AOP/LogAOP.cs"
new file mode 100644
index 0000000..50c3754
--- /dev/null
+++ "b/\351\241\271\347\233\256\344\273\243\347\240\201/WMS/WIDESEA_WMSServer/WIDESEA_Core/AOP/LogAOP.cs"
@@ -0,0 +1,328 @@
+锘縰sing Castle.DynamicProxy;
+using Microsoft.AspNetCore.Http;
+using Microsoft.AspNetCore.SignalR;
+using Newtonsoft.Json;
+using StackExchange.Profiling;
+using System;
+using System.Collections.Generic;
+using System.ComponentModel;
+using System.Linq;
+using System.Reflection;
+using System.Text;
+using System.Threading.Tasks;
+using WIDESEA_Core.Helper;
+using WIDESEA_Core.LogHelper;
+
+namespace WIDESEA_Core.AOP
+{
+    /// <summary>
+	/// 鎷︽埅鍣˙logLogAOP 缁ф壙IInterceptor鎺ュ彛
+	/// </summary>
+	public class LogAOP : IInterceptor
+    {
+        private readonly IHttpContextAccessor _accessor;
+
+        public LogAOP(IHttpContextAccessor accessor)
+        {
+            _accessor = accessor;
+        }
+
+        /// <summary>
+        /// 瀹炰緥鍖朓Interceptor鍞竴鏂规硶
+        /// </summary>
+        /// <param name="invocation">鍖呭惈琚嫤鎴柟娉曠殑淇℃伅</param>
+        public void Intercept(IInvocation invocation)
+        {
+            string UserName = _accessor.HttpContext?.User?.Identity?.Name;
+            string json;
+            try
+            {
+                if (invocation.Arguments.Any())
+                {
+                    json = JsonConvert.SerializeObject(invocation.Arguments);
+                }
+                else
+                {
+                    json = "鏃犲弬鏁�";
+                }
+            }
+            catch (Exception ex)
+            {
+                json = "鏃犳硶搴忓垪鍖栵紝鍙兘鏄叞濮嗚揪琛ㄨ揪寮忕瓑鍘熷洜閫犳垚锛屾寜鐓ф鏋朵紭鍖栦唬鐮�" + ex.ToString();
+            }
+
+            DateTime startTime = DateTime.Now;
+            AOPLogInfo apiLogAopInfo = new AOPLogInfo
+            {
+                RequestTime = startTime.ToString("yyyy-MM-dd hh:mm:ss fff"),
+                OpUserName = "銆愬綋鍓嶆搷浣滅敤鎴枫�戯細" + UserName,
+                RequestMethodName = "銆愬綋鍓嶆墽琛屾柟娉曘�戯細" + invocation.Method.Name,
+                RequestParamsName = "銆愭惡甯︾殑鍙傛暟鏈夈�戯細" + string.Join(", ", invocation.Arguments.Select(a => (a ?? "").ToString()).ToArray()),
+                RequestParamsData = json
+            };
+
+            var dataIntercept = $"";
+
+            try
+            {
+                MiniProfiler.Current.Step($"鎵ц{invocation.InvocationTarget}.{invocation.Method.Name}()鏂规硶 -> ");
+                //鍦ㄨ鎷︽埅鐨勬柟娉曟墽琛屽畬姣曞悗 缁х画鎵ц褰撳墠鏂规硶锛屾敞鎰忔槸琚嫤鎴殑鏄紓姝ョ殑
+                invocation.Proceed();
+
+                // 寮傛鑾峰彇寮傚父锛屽厛鎵ц
+                if (IsAsyncMethod(invocation.Method))
+                {
+                    #region 鏂规涓�
+
+                    //Wait task execution and modify return value
+                    if (invocation.Method.ReturnType == typeof(Task))
+                    {
+                        invocation.ReturnValue = InternalAsyncHelper.AwaitTaskWithPostActionAndFinally(
+                            (Task)invocation.ReturnValue,
+                            async () => await SuccessAction(invocation, apiLogAopInfo, startTime), /*鎴愬姛鏃舵墽琛�*/
+                            ex =>
+                            {
+                                LogEx(ex, apiLogAopInfo);
+                            });
+                    }
+                    //Task<TResult>
+                    else
+                    {
+                        invocation.ReturnValue = InternalAsyncHelper.CallAwaitTaskWithPostActionAndFinallyAndGetResult(
+                            invocation.Method.ReturnType.GenericTypeArguments[0],
+                            invocation.ReturnValue,
+                            //async () => await SuccessAction(invocation, dataIntercept),/*鎴愬姛鏃舵墽琛�*/
+                            async (o) => await SuccessAction(invocation, apiLogAopInfo, startTime, o), /*鎴愬姛鏃舵墽琛�*/
+                            ex =>
+                            {
+                                LogEx(ex, apiLogAopInfo);
+                            });
+                    }
+
+                    #endregion 鏂规涓�
+
+                    // 濡傛灉鏂规涓�涓嶈锛岃瘯璇曡繖涓柟妗�
+                    //#region 鏂规浜�
+
+                    //var type = invocation.Method.ReturnType;
+                    //var resultProperty = type.GetProperty("Result");
+                    //DateTime endTime = DateTime.Now;
+                    //string ResponseTime = (endTime - startTime).Milliseconds.ToString();
+                    //apiLogAopInfo.ResponseTime = endTime.ToString("yyyy-MM-dd hh:mm:ss fff");
+                    //apiLogAopInfo.ResponseIntervalTime = ResponseTime + "ms";
+                    //apiLogAopInfo.ResponseJsonData = JsonConvert.SerializeObject(resultProperty.GetValue(invocation.ReturnValue));
+
+                    ////dataIntercept += ($"銆愬搷搴旀椂闂淬�戯細{ResponseTime}ms\r\n");
+                    ////dataIntercept += ($"銆愭墽琛屽畬鎴愭椂闂淬�戯細{endTime.ToString("yyyy-MM-dd hh:mm:ss fff")}\r\n");
+                    ////dataIntercept += ($"銆愭墽琛屽畬鎴愮粨鏋溿�戯細{JsonConvert.SerializeObject(resultProperty.GetValue(invocation.ReturnValue))}\r\n");
+
+                    //Parallel.For(0, 1, e =>
+                    //{
+                    //    //LogLock.OutLogAOP("AOPLog", new string[] { dataIntercept });
+                    //    LogLock.OutLogAOP("AOPLog", new string[] { apiLogAopInfo.GetType().ToString() + " - ResponseJsonDataType:" + type, JsonConvert.SerializeObject(apiLogAopInfo) });
+                    //});
+
+                    //#endregion
+                }
+                else
+                {
+                    // 鍚屾1
+                    string jsonResult;
+                    try
+                    {
+                        jsonResult = JsonConvert.SerializeObject(invocation.ReturnValue);
+                    }
+                    catch (Exception ex)
+                    {
+                        jsonResult = "鏃犳硶搴忓垪鍖栵紝鍙兘鏄叞濮嗚揪琛ㄨ揪寮忕瓑鍘熷洜閫犳垚锛屾寜鐓ф鏋朵紭鍖栦唬鐮�" + ex.ToString();
+                    }
+
+                    var type = invocation.Method.ReturnType;
+                    var resultProperty = type.GetProperty("Result");
+                    DateTime endTime = DateTime.Now;
+                    string ResponseTime = (endTime - startTime).Milliseconds.ToString();
+                    apiLogAopInfo.ResponseTime = endTime.ToString("yyyy-MM-dd hh:mm:ss fff");
+                    apiLogAopInfo.ResponseIntervalTime = ResponseTime + "ms";
+                    apiLogAopInfo.ResponseJsonData = jsonResult;
+                    Parallel.For(0, 1, e =>
+                    {
+                        LogLock.OutLogAOP("AOPLog", new string[] { apiLogAopInfo.GetType().ToString(), JsonConvert.SerializeObject(apiLogAopInfo) });
+                    });
+                }
+            }
+            catch (Exception ex) // 鍚屾2
+            {
+                LogEx(ex, apiLogAopInfo);
+                throw;
+            }
+        }
+
+        private async Task SuccessAction(IInvocation invocation, AOPLogInfo apiLogAopInfo, DateTime startTime, object o = null)
+        {
+            DateTime endTime = DateTime.Now;
+            string ResponseTime = (endTime - startTime).Milliseconds.ToString();
+            apiLogAopInfo.ResponseTime = endTime.ToString("yyyy-MM-dd hh:mm:ss fff");
+            apiLogAopInfo.ResponseIntervalTime = ResponseTime + "ms";
+            apiLogAopInfo.ResponseJsonData = JsonConvert.SerializeObject(o);
+
+            await Task.Run(() =>
+            {
+                Parallel.For(0, 1, e =>
+                {
+                    //LogLock.OutSql2Log("AOPLog", new string[] { JsonConvert.SerializeObject(apiLogAopInfo) });
+                    LogLock.OutLogAOP("AOPLog", new string[] { apiLogAopInfo.GetType().ToString(), JsonConvert.SerializeObject(apiLogAopInfo) });
+                });
+            });
+        }
+
+        private void LogEx(Exception ex, AOPLogInfo dataIntercept)
+        {
+            if (ex != null)
+            {
+                //鎵ц鐨� service 涓紝鏀跺綍寮傚父
+                MiniProfiler.Current.CustomTiming("Errors锛�", ex.Message);
+                //鎵ц鐨� service 涓紝鎹曡幏寮傚父
+                AOPLogExInfo apiLogAopExInfo = new AOPLogExInfo
+                {
+                    ExMessage = ex.Message,
+                    InnerException = "InnerException-鍐呴儴寮傚父:\r\n" + (ex.InnerException == null ? "" : ex.InnerException.InnerException.ToString()) +
+                                     "\r\nStackTrace-鍫嗘爤璺熻釜:\r\n" + (ex.StackTrace == null ? "" : ex.StackTrace.ToString()),
+                    ApiLogAopInfo = dataIntercept
+                };
+                // 寮傚父鏃ュ織閲屾湁璇︾粏鐨勫爢鏍堜俊鎭�
+                Parallel.For(0, 1, e =>
+                {
+                    LogLock.OutLogAOP("AOPLogEx", new string[] { apiLogAopExInfo.GetType().ToString(), JsonConvert.SerializeObject(apiLogAopExInfo) });
+                });
+            }
+        }
+
+        public static bool IsAsyncMethod(MethodInfo method)
+        {
+            return
+                method.ReturnType == typeof(Task) ||
+                method.ReturnType.IsGenericType && method.ReturnType.GetGenericTypeDefinition() == typeof(Task<>)
+            ;
+        }
+    }
+
+    internal static class InternalAsyncHelper
+    {
+        public static async Task AwaitTaskWithPostActionAndFinally(Task actualReturnValue, Func<Task> postAction, Action<Exception> finalAction)
+        {
+            Exception exception = null;
+
+            try
+            {
+                await actualReturnValue;
+                await postAction();
+            }
+            catch (Exception ex)
+            {
+                exception = ex;
+            }
+            finally
+            {
+                finalAction(exception);
+            }
+        }
+
+        public static async Task<T> AwaitTaskWithPostActionAndFinallyAndGetResult<T>(Task<T> actualReturnValue, Func<object, Task> postAction,
+            Action<Exception> finalAction)
+        {
+            Exception exception = null;
+            try
+            {
+                var result = await actualReturnValue;
+                await postAction(result);
+                return result;
+            }
+            catch (Exception ex)
+            {
+                exception = ex;
+                throw;
+            }
+            finally
+            {
+                finalAction(exception);
+            }
+        }
+
+        public static object CallAwaitTaskWithPostActionAndFinallyAndGetResult(Type taskReturnType, object actualReturnValue,
+            Func<object, Task> action, Action<Exception> finalAction)
+        {
+            return typeof(InternalAsyncHelper)
+                .GetMethod("AwaitTaskWithPostActionAndFinallyAndGetResult", BindingFlags.Public | BindingFlags.Static)
+                .MakeGenericMethod(taskReturnType)
+                .Invoke(null, new object[] { actualReturnValue, action, finalAction });
+        }
+    }
+
+    public class AOPLogInfo
+    {
+        /// <summary>
+        /// 璇锋眰鏃堕棿
+        /// </summary>
+        [Description("璇锋眰鏃堕棿")]
+        public string RequestTime { get; set; } = string.Empty;
+
+        /// <summary>
+        /// 鎿嶄綔浜哄憳
+        /// </summary>
+        [Description("鎿嶄綔浜哄憳")]
+        public string OpUserName { get; set; } = string.Empty;
+
+        /// <summary>
+        /// 璇锋眰鏂规硶鍚�
+        /// </summary>
+        [Description("璇锋眰鏂规硶鍚�")]
+        public string RequestMethodName { get; set; } = string.Empty;
+
+        /// <summary>
+        /// 璇锋眰鍙傛暟鍚�
+        /// </summary>
+        [Description("璇锋眰鍙傛暟鍚�")]
+        public string RequestParamsName { get; set; } = string.Empty;
+
+        /// <summary>
+        /// 璇锋眰鍙傛暟鏁版嵁JSON
+        /// </summary>
+        [Description("璇锋眰鍙傛暟鏁版嵁JSON")]
+        public string RequestParamsData { get; set; } = string.Empty;
+
+        /// <summary>
+        /// 璇锋眰鍝嶅簲闂撮殧鏃堕棿
+        /// </summary>
+        [Description("璇锋眰鍝嶅簲闂撮殧鏃堕棿")]
+        public string ResponseIntervalTime { get; set; } = string.Empty;
+
+        /// <summary>
+        /// 鍝嶅簲鏃堕棿
+        /// </summary>
+        [Description("鍝嶅簲鏃堕棿")]
+        public string ResponseTime { get; set; } = string.Empty;
+
+        /// <summary>
+        /// 鍝嶅簲缁撴灉
+        /// </summary>
+        [Description("鍝嶅簲缁撴灉")]
+        public string ResponseJsonData { get; set; } = string.Empty;
+    }
+
+    public class AOPLogExInfo
+    {
+        public AOPLogInfo ApiLogAopInfo { get; set; }
+
+        /// <summary>
+        /// 寮傚父
+        /// </summary>
+        [Description("寮傚父")]
+        public string InnerException { get; set; } = string.Empty;
+
+        /// <summary>
+        /// 寮傚父淇℃伅
+        /// </summary>
+        [Description("寮傚父淇℃伅")]
+        public string ExMessage { get; set; } = string.Empty;
+    }
+}
\ No newline at end of file

--
Gitblit v1.9.3