From fe596f9db05103917c9257348edcbd3ecb5b46e8 Mon Sep 17 00:00:00 2001
From: yanjinhui <3306209981@qq.com>
Date: 星期四, 16 四月 2026 19:12:38 +0800
Subject: [PATCH] Merge branch 'master' of http://115.159.85.185:8098/r/RuiShengZhiNeng/GaoPuLiTiKu
---
代码管理/WCS/WIDESEAWCS_Server/WIDESEAWCS_Server/Filter/Log/LoggerNew.cs | 431 +++++++++++++++++++++++++++++++++++++++++++++++++++++
1 files changed, 431 insertions(+), 0 deletions(-)
diff --git "a/\344\273\243\347\240\201\347\256\241\347\220\206/WCS/WIDESEAWCS_Server/WIDESEAWCS_Server/Filter/Log/LoggerNew.cs" "b/\344\273\243\347\240\201\347\256\241\347\220\206/WCS/WIDESEAWCS_Server/WIDESEAWCS_Server/Filter/Log/LoggerNew.cs"
new file mode 100644
index 0000000..bd6abe2
--- /dev/null
+++ "b/\344\273\243\347\240\201\347\256\241\347\220\206/WCS/WIDESEAWCS_Server/WIDESEAWCS_Server/Filter/Log/LoggerNew.cs"
@@ -0,0 +1,431 @@
+锘縰sing SqlSugar;
+using System.Collections.Concurrent;
+using System.Text;
+using WIDESEAWCS_Core.HttpContextUser;
+using WIDESEAWCS_Core.Seed;
+using WIDESEAWCS_Model.Models;
+using System.Security.Cryptography;
+using WIDESEAWCS_Core.Helper;
+using Newtonsoft.Json.Linq;
+using WIDESEAWCS_DTO.RGV.FOURBOT;
+using WIDESEAWCS_DTO.WMS;
+using WIDESEAWCS_DTO;
+
+namespace WIDESEAWCS_Core.LogHelper
+{
+ public static class LoggerNew
+ {
+ // 鐢ㄤ簬缂撳瓨褰撳ぉ宸插瓨鍦ㄧ殑鏃ュ織锛坘ey: 鏃ユ湡+ApiCode+璇锋眰鍝堝笇+鍝嶅簲鍝堝笇锛�
+ private static ConcurrentDictionary<string, Dt_InterfaceLog> _cacheLogs = new ConcurrentDictionary<string, Dt_InterfaceLog>();
+ // 闃熷垪鐢ㄤ簬瀛樺偍闇�瑕佹柊澧炴垨鏇存柊鐨勬棩蹇�
+ public static ConcurrentQueue<Dt_InterfaceLog> loggerQueueData = new ConcurrentQueue<Dt_InterfaceLog>();
+
+ // 姣忓ぉ鍑屾櫒娓呯┖缂撳瓨
+ private static DateTime _lastClearDate = DateTime.Now.Date;
+
+ static LoggerNew()
+ {
+ Task.Run(() =>
+ {
+ StartWriteLog();
+ });
+
+ // 鍚姩涓�涓悗鍙颁换鍔★紝姣忓ぉ鍑屾櫒娓呯┖缂撳瓨
+ Task.Run(() =>
+ {
+ while (true)
+ {
+ Thread.Sleep(60000); // 姣忓垎閽熸鏌ヤ竴娆�
+ DateTime today = DateTime.Now.Date;
+ if (_lastClearDate < today)
+ {
+ _cacheLogs.Clear();
+ _lastClearDate = today;
+ Console.WriteLine($"Logger缂撳瓨宸叉竻绌猴紝鏃ユ湡锛歿today:yyyy-MM-dd}");
+ }
+ }
+ });
+ }
+
+ static void StartWriteLog()
+ {
+ List<Dt_InterfaceLog> batchList = new List<Dt_InterfaceLog>();
+
+ while (true)
+ {
+ try
+ {
+ if (loggerQueueData.Count() > 0 && batchList.Count < 500)
+ {
+ DequeueToBatchList(batchList);
+ continue;
+ }
+
+ Thread.Sleep(5000);
+
+ if (batchList.Count == 0) { continue; }
+
+ SqlSugarClient sugarClient = new SqlSugarClient(new ConnectionConfig()
+ {
+ ConnectionString = DBContext.GetMainConnectionDb().Connection,
+ IsAutoCloseConnection = true,
+ DbType = DBContext.DbType,
+ });
+
+ try
+ {
+ sugarClient.BeginTran(); // 寮�鍚簨鍔�
+
+ var toInsert = new List<Dt_InterfaceLog>();
+ var toUpdate = new List<Dt_InterfaceLog>();
+
+ foreach (var log in batchList)
+ {
+ // 濡傛灉宸茬粡鏈� Id 鎴栬�� IsExisting 鏍囧織锛岀洿鎺ュ鐞�
+ if (log.Id > 0)
+ {
+ toUpdate.Add(log);
+ continue;
+ }
+
+ // 鏍规嵁鍝堝笇鍊兼煡璇㈡槸鍚﹀凡瀛樺湪
+ var existing = sugarClient.Queryable<Dt_InterfaceLog>()
+ .First(x => x.RequestParametersHash == log.RequestParametersHash
+ && x.ResponseParametersHash == log.ResponseParametersHash
+ && x.ApiCode == log.ApiCode
+ && SqlFunc.DateIsSame(x.CreateDate, DateTime.Now)); // 鍚屼竴澶�
+
+ if (existing != null)
+ {
+ // 宸插瓨鍦紝鏇存柊
+ log.Id = existing.Id;
+ log.PushFrequency = existing.PushFrequency + 1; // 鍙犲姞娆℃暟
+ log.ModifyDate = DateTime.Now;
+ toUpdate.Add(log);
+
+ // 鏇存柊缂撳瓨涓殑 Id
+ string cacheKey = GenerateCacheKey(log.ApiCode, log.RequestParametersHash, log.ResponseParametersHash);
+ if (_cacheLogs.TryGetValue(cacheKey, out var cachedLog))
+ {
+ cachedLog.Id = existing.Id;
+ }
+ }
+ else
+ {
+ // 涓嶅瓨鍦紝鏂板
+ toInsert.Add(log);
+ }
+ }
+
+ // 鎵归噺鏂板
+ if (toInsert.Any())
+ {
+ int rows = sugarClient.Fastest<Dt_InterfaceLog>().BulkCopy(toInsert);
+
+ // 鑾峰彇鏂板鏃ュ織鐨勮嚜澧濱D骞舵洿鏂扮紦瀛�
+ foreach (var insertedLog in toInsert)
+ {
+ var savedLog = sugarClient.Queryable<Dt_InterfaceLog>()
+ .First(x => x.RequestParametersHash == insertedLog.RequestParametersHash
+ && x.ResponseParametersHash == insertedLog.ResponseParametersHash);
+ if (savedLog != null)
+ {
+ string cacheKey = GenerateCacheKey(insertedLog.ApiCode,
+ insertedLog.RequestParametersHash, insertedLog.ResponseParametersHash);
+ if (_cacheLogs.TryGetValue(cacheKey, out var cachedLog))
+ {
+ cachedLog.Id = savedLog.Id;
+ }
+ }
+ }
+ }
+
+ // 鎵归噺鏇存柊鎺ㄩ�佹鏁�
+ if (toUpdate.Any())
+ {
+ foreach (var log in toUpdate)
+ {
+ sugarClient.Updateable<Dt_InterfaceLog>()
+ .SetColumns(it => new Dt_InterfaceLog
+ {
+ PushFrequency = log.PushFrequency,
+ PushState = log.PushState,
+ Remark = log.Remark,
+ //CreateDate = log.CreateDate
+ ModifyDate = log.ModifyDate
+ })
+ .Where(it => it.Id == log.Id)
+ .ExecuteCommand();
+ }
+ }
+
+ sugarClient.CommitTran(); // 鎻愪氦浜嬪姟
+ }
+ catch (Exception ex)
+ {
+ sugarClient.RollbackTran(); // 鍥炴粴浜嬪姟
+ Console.WriteLine($"澶勭悊鏃ュ織鎵规澶辫触: {ex.Message}");
+ }
+ finally
+ {
+ batchList.Clear();
+ }
+ }
+ catch (Exception ex)
+ {
+ Console.WriteLine(ex.ToString());
+ }
+ }
+ }
+
+ private static void DequeueToBatchList(List<Dt_InterfaceLog> batchList)
+ {
+ if (loggerQueueData.TryDequeue(out Dt_InterfaceLog log) && log != null)
+ {
+ batchList.Add(log);
+ }
+ }
+
+ /// <summary>
+ /// 璁$畻瀛楃涓茬殑SHA256鍝堝笇鍊�
+ /// </summary>
+ private static string ComputeHash(string input)
+ {
+ if (string.IsNullOrEmpty(input))
+ return string.Empty;
+
+ using (SHA256 sha256 = SHA256.Create())
+ {
+ byte[] bytes = Encoding.UTF8.GetBytes(input);
+ byte[] hashBytes = sha256.ComputeHash(bytes);
+ return BitConverter.ToString(hashBytes).Replace("-", "").ToLower();
+ }
+ }
+
+ /// <summary>
+ /// 鐢熸垚缂撳瓨Key
+ /// </summary>
+ private static string GenerateCacheKey(string apiCode, string requestHash, string responseHash)
+ {
+ string today = DateTime.Now.ToString("yyyy-MM-dd");
+ return $"{today}_{apiCode}_{requestHash}_{responseHash}";
+ }
+
+ /// <summary>
+ /// 鑾峰彇鎴栧垱寤烘棩蹇楋紙鐢ㄤ簬鍙犲姞鎺ㄩ�佹鏁帮級
+ /// </summary>
+ /// <param name="apiCode">缂栧彿</param>
+ /// <param name="apiName">鍚嶇О</param>
+ /// <param name="apiAddress">鍦板潃</param>
+ /// <param name="requestParameters">璇锋眰鍐呭</param>
+ /// <param name="responseParameters">鍝嶅簲鍐呭</param>
+ /// <param name="pushState">鐘舵��</param>
+ /// <param name="requestorUserIP">璇锋眰鐢ㄦ埛IP</param>
+ /// <param name="requestor">璇锋眰鏂�</param>
+ /// <param name="recipient">鎺ユ敹鏂�</param>
+ /// <param name="remark">澶囨敞</param>
+ /// <returns></returns>
+ private static Dt_InterfaceLog GetOrCreateLog(string apiCode, string apiName, string apiAddress,
+ string requestParameters, string responseParameters, int pushState,
+ string requestorUserIP, string requestor, string recipient, string remark)
+ {
+ string requestHash = ComputeHash(requestParameters);
+ string responseHash = ComputeHash(responseParameters);
+ string cacheKey = GenerateCacheKey(apiCode, requestHash, responseHash);
+
+ // 灏濊瘯浠庣紦瀛樹腑鑾峰彇
+ if (_cacheLogs.TryGetValue(cacheKey, out Dt_InterfaceLog existingLog))
+ {
+ // 瀛樺湪鐩稿悓鍙傛暟鐨勬棩蹇楋紝澧炲姞鎺ㄩ�佹鏁�
+ existingLog.PushFrequency++;
+ existingLog.PushState = pushState; // 鏇存柊鎺ㄩ�佺姸鎬�
+ existingLog.Remark = remark; // 鏇存柊澶囨敞
+ //existingLog.CreateDate = DateTime.Now; // 鏇存柊鏃堕棿
+ existingLog.ModifyDate = DateTime.Now; // 鏇存柊鏃堕棿
+
+ // 杩斿洖鐜版湁鏃ュ織锛堥渶瑕佹洿鏂版暟鎹簱锛�
+ return existingLog;
+ }
+ else
+ {
+ // 涓嶅瓨鍦紝鍒涘缓鏂版棩蹇�
+ var newLog = new Dt_InterfaceLog
+ {
+ ApiCode = apiCode,
+ ApiName = apiName,
+ ApiAddress = apiAddress,
+ PushFrequency = 1,
+ PushState = pushState,
+ RequestorUserIP = requestorUserIP,
+ Requestor = requestor,
+ RequestParameters = requestParameters,
+ RequestParametersHash = requestHash,
+ Recipient = recipient,
+ ResponseParameters = responseParameters,
+ ResponseParametersHash = responseHash,
+ Remark = remark,
+ Creater = "System",
+ CreateDate = DateTime.Now
+ };
+
+ // 鍔犲叆缂撳瓨
+ _cacheLogs.TryAdd(cacheKey, newLog);
+
+ return newLog;
+ }
+ }
+
+ /// <summary>
+ /// 娣诲姞鎺ュ彛鏃ュ織锛堝甫URL銆佽姹傚弬鏁般�佸搷搴斿弬鏁般�佸紑濮嬫椂闂达級
+ /// </summary>
+ public static void Add(string apiCode, string apiName, string apiAddress,
+ string requestParameters, string responseParameters,
+ int pushState = 0, string recipient = "", string remark = "")
+ {
+ Dt_InterfaceLog log = null;
+ try
+ {
+ // 鑾峰彇褰撳墠鐢ㄦ埛
+ IUser? user = App.User;
+
+ // 鑾峰彇鎴栧垱寤烘棩蹇楋紙鑷姩澶勭悊鍙犲姞锛�
+ log = GetOrCreateLog(apiCode, apiName, apiAddress,
+ requestParameters, responseParameters, pushState,
+ "", user?.UserName ?? "", recipient, remark);
+ }
+ catch (Exception exception)
+ {
+ // 濡傛灉鍙戠敓寮傚父锛屽垱寤哄熀纭�鏃ュ織瀵硅薄
+ log = log ?? new Dt_InterfaceLog
+ {
+ ApiCode = apiCode,
+ ApiName = apiName,
+ ApiAddress = apiAddress,
+ PushFrequency = 1,
+ PushState = pushState,
+ RequestParameters = requestParameters,
+ ResponseParameters = responseParameters,
+ Creater = "System",
+ Remark = $"璁板綍鏃ュ織鏃跺彂鐢熷紓甯革細{exception.Message}"
+ };
+ }
+
+ // 娣诲姞绯荤粺鏃ュ織
+ loggerQueueData.Enqueue(log);
+ }
+
+ /// <summary>
+ /// 娣诲姞鎺ュ彛鏃ュ織锛堜粠HttpContext鑷姩鑾峰彇淇℃伅锛�
+ /// </summary>
+ /// <param name="requestParameters">璇锋眰鍐呭</param>
+ /// <param name="responseParameters">鍝嶅簲鍐呭</param>
+ /// <param name="apiCode">鎺ュ彛缂栧彿</param>
+ /// <param name="apiName">鎺ュ彛鍚嶇О</param>
+ /// <param name="pushState">鎺ㄩ�佺姸鎬�</param>
+ /// <param name="recipient">鎺ユ敹鏂�</param>
+ /// <param name="remark">澶囨敞</param>
+ public static void Add(string requestParameters, string responseParameters, HttpContext context, string apiCode = "", string apiName = "", int pushState = 0, string recipient = "WCS", string remark = "")
+ {
+ Dt_InterfaceLog log = null;
+ try
+ {
+ // 濡傛灉璇锋眰鏂规硶涓篛PTIONS锛屽垯杩斿洖
+ if (context.Request.Method == "OPTIONS") return;
+
+ #region 鏁版嵁杞崲
+
+ // 瑙f瀽澶栧眰 JSON
+ JObject outerObj = JObject.Parse(requestParameters);
+
+ // 鑾峰彇 BodyData 鐨勫�硷紙瀹冩槸涓�涓瓧绗︿覆锛�
+ requestParameters = outerObj["BodyData"]?.ToString() ?? requestParameters;
+
+ // 鏋勫缓瀹屾暣鐨勬帴鍙e湴鍧�
+ string apiAddress = context.Request.Scheme + "://" + context.Request.Host + context.Request.PathBase + context.Request.Path;
+ // 鑾峰彇瀹㈡埛绔疘P
+ string clientIP = GetClientIP(context)?.Replace("::ffff:", "") ?? "";
+ string requestor = "";//璇锋眰鏂�
+ if (apiAddress.Contains("/api/WMS"))
+ {
+ requestor = "WMS";//绉掍紭
+ var wMSReturn = responseParameters.DeserializeObject<WMSReturn>();
+ pushState = wMSReturn.code == 0 ? 1 : 2;
+ }
+ else if (apiAddress.Contains("/api/KHAGV"))
+ {
+ requestor = "娴峰悍AGV";
+ var hIKROBOTReturn = responseParameters.DeserializeObject<HIKROBOTReturn>();
+ pushState = hIKROBOTReturn.code == "SUCCESS" ? 1 : 2;
+ }
+ else if (apiAddress.Contains("/api/KLS"))
+ {
+ requestor = "鍑箰澹獳GV";
+ ReturnGALAXIS returnGALAXIS = responseParameters.DeserializeObject<ReturnGALAXIS>();
+ pushState = returnGALAXIS.returnStatus == 0 ? 1 : 2;
+ }
+ else if (apiAddress.Contains("/api/RGV"))
+ {
+ requestor = "鍥涘悜绌挎杞�";//鏃疯娌冲浘
+ FOURBOTReturn fOURBOTReturn = responseParameters.DeserializeObject<FOURBOTReturn>();
+ pushState = fOURBOTReturn.returnCode == 0 ? 1 : 2;
+ }
+ apiCode = apiAddress.Split("/").Last();
+ apiName = AppSettings.Configuration.GetValue($"{requestor}:{apiCode}", apiCode);
+ #endregion
+
+ // 鑾峰彇鎴栧垱寤烘棩蹇楋紙鑷姩澶勭悊鍙犲姞锛�
+ log = GetOrCreateLog(apiCode, apiName, apiAddress,
+ requestParameters, responseParameters, pushState,
+ clientIP, requestor, recipient, remark);
+ }
+ catch (Exception exception)
+ {
+ // 濡傛灉鍙戠敓寮傚父锛屽垱寤哄熀纭�鏃ュ織瀵硅薄
+ log = log ?? new Dt_InterfaceLog
+ {
+ ApiCode = apiCode,
+ ApiName = apiName,
+ PushFrequency = 1,
+ PushState = pushState,
+ RequestParameters = requestParameters,
+ ResponseParameters = responseParameters,
+ Creater = "System",
+ Remark = $"璁板綍鏃ュ織鏃跺彂鐢熷紓甯革細{exception.Message}"
+ };
+ }
+
+ // 娣诲姞绯荤粺鏃ュ織
+ loggerQueueData.Enqueue(log);
+ }
+
+ /// <summary>
+ /// 鎵嬪姩澧炲姞鎺ㄩ�佹鏁帮紙鐢ㄤ簬閲嶈瘯鍦烘櫙锛�
+ /// </summary>
+ public static void IncrementPushCount(string apiCode, string requestParameters, string responseParameters)
+ {
+ string requestHash = ComputeHash(requestParameters);
+ string responseHash = ComputeHash(responseParameters);
+ string cacheKey = GenerateCacheKey(apiCode, requestHash, responseHash);
+
+ if (_cacheLogs.TryGetValue(cacheKey, out Dt_InterfaceLog existingLog))
+ {
+ existingLog.PushFrequency++;
+ loggerQueueData.Enqueue(existingLog);
+ }
+ }
+
+ public static string GetClientIP(HttpContext context)
+ {
+ // 鑾峰彇璇锋眰澶翠腑鐨刋-Forwarded-For瀛楁锛屽苟灏嗗叾杞崲涓哄瓧绗︿覆
+ var ip = context.Request.Headers["X-Forwarded-For"].ObjToString();
+ // 濡傛灉X-Forwarded-For瀛楁涓虹┖锛屽垯鑾峰彇杩滅▼IP鍦板潃
+ if (string.IsNullOrEmpty(ip))
+ {
+ ip = context.Connection.RemoteIpAddress.ObjToString();
+ }
+
+ // 杩斿洖IP鍦板潃
+ return ip;
+ }
+ }
+}
\ No newline at end of file
--
Gitblit v1.9.3