From cc1a70b8af38690e0ab72228e996a8859565cd89 Mon Sep 17 00:00:00 2001 From: dengjunjie <dengjunjie@hnkhzn.com> Date: 星期一, 09 六月 2025 17:15:30 +0800 Subject: [PATCH] 1 --- 代码管理/WMS/WIDESEA_WMSServer/WIDESEA_Core/LogHelper/Logger.cs | 378 +++++++++++++++++++++++++++++++++++++---------------- 1 files changed, 265 insertions(+), 113 deletions(-) diff --git "a/\344\273\243\347\240\201\347\256\241\347\220\206/WMS/WIDESEA_WMSServer/WIDESEA_Core/LogHelper/Logger.cs" "b/\344\273\243\347\240\201\347\256\241\347\220\206/WMS/WIDESEA_WMSServer/WIDESEA_Core/LogHelper/Logger.cs" index 4995e84..1d9a8b7 100644 --- "a/\344\273\243\347\240\201\347\256\241\347\220\206/WMS/WIDESEA_WMSServer/WIDESEA_Core/LogHelper/Logger.cs" +++ "b/\344\273\243\347\240\201\347\256\241\347\220\206/WMS/WIDESEA_WMSServer/WIDESEA_Core/LogHelper/Logger.cs" @@ -1,158 +1,310 @@ -锘� -using Microsoft.AspNetCore.Http; -using Newtonsoft.Json; +锘縰sing Microsoft.AspNetCore.Http; +using Microsoft.OpenApi.Models; using SqlSugar; +using StackExchange.Profiling.Internal; using System; +using System.Collections.Concurrent; using System.Collections.Generic; +using System.ComponentModel; +using System.Data; +using System.IO; using System.Linq; +using System.Reflection; +using System.Runtime.Serialization.Formatters; using System.Text; using System.Threading.Tasks; +using System.Xml.Linq; using WIDESEA_Core.DB; +using WIDESEA_Core.Enums; using WIDESEA_Core.Helper; using WIDESEA_Core.HttpContextUser; using WIDESEA_Core.Seed; namespace WIDESEA_Core.LogHelper { - public class Logger + public static class Logger { - - public static void Debug(string message) + public static ConcurrentQueue<dynamic> loggerQueueData = new ConcurrentQueue<dynamic>(); + static Logger() { - - } - - public static void Debug(string message, Exception exception) - { - - } - - public static void Info(string message) - { - - } - - public static void Info(string message, Exception exception) - { - - } - - public static void Warn(string message) - { - - } - - public static void Warning(string message, Exception exception) - { - - } - - public static void Error(string message) - { - - } - - public static void Error(string message, Exception exception) - { - - } - - public static void Fatal(string message) - { - - } - - public static void Fatal(string message, Exception exception) - { - - } - public static void Write_Log(string groupName, string logName, string content, object data = null) - { - DateTime nowTime = DateTime.Now; - string basePath = System.Environment.CurrentDirectory + "/Log/" + $"/{groupName}/{nowTime.ToString("yyyy-MM-dd")}"; - //濡傛灉鏃ュ織鏂囦欢鐩綍涓嶅瓨鍦�,鍒欏垱寤� - if (!Directory.Exists(basePath)) + Task.Run(() => { - Directory.CreateDirectory(basePath); - } - try + StartWriteLog(); + }); + + } + + static void StartWriteLog() + { + DataTable queueTable = CreateEmptyTable(); + while (true) { - FileStream fs = new FileStream(basePath + "/" + logName + $"{nowTime.ToString("yyMMdd")}.txt", FileMode.Append); - StreamWriter strwriter = new StreamWriter(fs); try { - strwriter.WriteLine(nowTime.ToString() + "." + nowTime.Millisecond); - strwriter.WriteLine(content); - if (data != null) + //濡傛灉闃熷垪涓湁鏁版嵁涓旈槦鍒楄〃涓殑琛屾暟灏忎簬500锛屽垯灏嗛槦鍒椾腑鐨勬暟鎹啓鍏ラ槦鍒楄〃 + if (loggerQueueData.Count() > 0 && queueTable.Rows.Count < 500) { - strwriter.WriteLine(JsonConvert.SerializeObject(data)); + DequeueToTable(queueTable); continue; } - strwriter.WriteLine("-------------------------------"); - strwriter.WriteLine(); - strwriter.Flush(); + //姣�5绉掑啓涓�娆℃暟鎹� + Thread.Sleep(5000); + + //濡傛灉闃熷垪琛ㄤ腑鐨勮鏁颁负0锛屽垯璺宠繃鏈寰幆 + if (queueTable.Rows.Count == 0) { continue; } + + //鍒涘缓SqlSugarClient瀵硅薄锛岀敤浜庤繛鎺ユ暟鎹簱 + SqlSugarClient sugarClient = new SqlSugarClient(new ConnectionConfig() + { + ConnectionString = DBContext.GetMainConnectionDb().Connection, + IsAutoCloseConnection = true, + DbType = MainDb.DbType, + }); + + //灏嗛槦鍒楄〃涓殑鏁版嵁鎵归噺鎻掑叆鏁版嵁搴� + int rows = sugarClient.Fastest<DataTable>().AS("Sys_Log").BulkCopy(queueTable); + + //娓呯┖闃熷垪琛� + queueTable.Clear(); } - catch { } - finally + catch (Exception ex) { - strwriter.Close(); - fs.Close(); + //鎵撳嵃寮傚父淇℃伅 + Console.WriteLine(ex.ToString()); } } - catch { } } - public static void WriteApiLog2DB(HttpContext context, string requestParameter, DateTime beginDate, string responseParameter, DateTime endDate, LoggerStatus loggerStatus) + private static void DequeueToTable(DataTable queueTable) { + loggerQueueData.TryDequeue(out dynamic log); + if (log != null) + { + DataRow row = queueTable.NewRow(); + // 濡傛灉log鐨凚eginDate涓虹┖鎴栬�匓eginDate鐨勫勾浠藉皬浜�2010锛屽垯灏咮eginDate璁剧疆涓哄綋鍓嶆椂闂� + if (log.BeginDate == null || log.BeginDate?.Year < 2010) + { + log.BeginDate = DateTime.Now; + } + // 濡傛灉log鐨凟ndDate涓虹┖锛屽垯灏咵ndDate璁剧疆涓哄綋鍓嶆椂闂� + if (log.EndDate == null) + { + log.EndDate = DateTime.Now; + } + // row["Id"] = log.Id; + // 灏哛equestParam涓殑鎹㈣绗︽浛鎹负绌哄瓧绗︿覆 + row["RequestParam"] = log.RequestParam?.Replace("\r\n", "").Replace("\n", ""); + // 灏哛esponseParam涓殑鎹㈣绗︽浛鎹负绌哄瓧绗︿覆 + row["ResponseParam"] = log.ResponseParam?.Replace("\r\n", "").Replace("\n", ""); + row["Success"] = log.Success ?? -1; + // 灏咮eginDate璁剧疆涓簂og鐨凚eginDate + row["BeginDate"] = log.BeginDate; + // 灏咵ndDate璁剧疆涓簂og鐨凟ndDate + row["EndDate"] = log.EndDate; + // 璁$畻ElapsedTime锛屽嵆EndDate鍑忓幓BeginDate鐨勬绉掓暟 + row["ElapsedTime"] = ((DateTime)log.EndDate - (DateTime)log.BeginDate).TotalMilliseconds; + // 灏哢serIP璁剧疆涓簂og鐨刄serIP + row["UserIP"] = log.UserIP; + // 灏哢rl璁剧疆涓簂og鐨刄rl + row["Url"] = log.Url; + // 濡傛灉log鐨刄serId涓虹┖锛屽垯灏哢serId璁剧疆涓�-1锛屽惁鍒欒缃负log鐨刄serId + row["UserId"] = log.UserId ?? -1; + // 灏哢serName璁剧疆涓簂og鐨刄serName + row["UserName"] = log.UserName; + row["MethodName"] = log.MethodName; + row["Methodremark"] = log.Methodremark; + // 灏唕ow娣诲姞鍒皅ueueTable涓� + queueTable.Rows.Add(row); + } + } + + private static DataTable CreateEmptyTable() + { + DataTable queueTable = new DataTable(); + queueTable.Columns.Add("BeginDate", Type.GetType("System.DateTime")); + queueTable.Columns.Add("ElapsedTime", Type.GetType("System.Int32")); + queueTable.Columns.Add("EndDate", Type.GetType("System.DateTime")); + queueTable.Columns.Add("RequestParam", typeof(string)); + queueTable.Columns.Add("ResponseParam", typeof(string)); + queueTable.Columns.Add("Success", Type.GetType("System.Int32")); + queueTable.Columns.Add("Url", typeof(string)); + queueTable.Columns.Add("UserIP", typeof(string)); + queueTable.Columns.Add("UserName", typeof(string)); + queueTable.Columns.Add("UserId", Type.GetType("System.Int32")); + queueTable.Columns.Add("MethodName", typeof(string)); + queueTable.Columns.Add("Methodremark", typeof(string)); + //queueTable.Columns.Add("ServiceIP", typeof(string)); + //queueTable.Columns.Add("BrowserType", typeof(string)); + //queueTable.Columns.Add("Role_Id", Type.GetType("System.Int32")); + return queueTable; + } + + public static void Add(string requestParameter, string responseParameter) + { + dynamic log = null; + string MethodName = string.Empty; + string Methodremark = string.Empty; try { - if (context.Request.Method == "OPTIONS") return; - + //鑾峰彇褰撳墠HttpContext + HttpContext context = App.HttpContext; + //濡傛灉HttpContext涓虹┖锛屽垯杩斿洖 if (context == null) { - Console.WriteLine($"鏈幏鍙栧埌httpcontext淇℃伅,reqParam:{requestParameter},respParam:{responseParameter},success:{loggerStatus}"); return; } - Dictionary<string, object> dic = new Dictionary<string, object> + //濡傛灉璇锋眰鏂规硶涓篛PTIONS锛屽垯杩斿洖 + if (context.Request.Method == "OPTIONS") return; + //鑾峰彇RequestLogModel瀹炰緥 + RequestLogModel logModel = (context.RequestServices.GetService(typeof(RequestLogModel)) as RequestLogModel) ?? new RequestLogModel { RequestDate = DateTime.Now }; + #region 鑾峰彇鎺ュ彛娉ㄩ噴 + try { - {"BeginDate",beginDate }, - {"ElapsedTime",(endDate - beginDate).TotalMilliseconds.DoubleToInt() }, - {"EndDate",endDate }, - {"RequestParam",requestParameter }, - {"ResponseParam",responseParameter }, - {"Success",1 }, - {"Url",context.Request.Path.Value??"" }, - {"UserIP",context.GetUserIp() }, - {"UserName","App.User?.Name" }, - {"User_Id","0" } + string path = context.Request.Path; + var names = path.Split('/'); + var basePath = AppContext.BaseDirectory + "WIDESEA_WMSServer"; + Assembly assembly = Assembly.LoadFrom(basePath); + List<Type> types = assembly.GetTypes().Where(x => x.Name.Contains(names[2] + "Controller")).ToList(); + if (types.Count > 0) + { + //MethodInfo methodInfo = types.First().GetMethod("login"); + MethodInfo methodInfo = types.First().GetMethods() + .FirstOrDefault(m => m.Name.Equals(names[3], StringComparison.OrdinalIgnoreCase)); + if (methodInfo != null) + { + MethodName = methodInfo.Name; + string xmlPath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, methodInfo.DeclaringType.Assembly.GetName().Name + ".xml"); + //if (!File.Exists(xmlPath)) return "XML documentation file not found."; // 妫�鏌ユ枃浠舵槸鍚﹀瓨鍦� + // 鍔犺浇XML鏂囨。骞惰В鏋愭憳瑕佷俊鎭� + XDocument xdoc = XDocument.Load(xmlPath); + string membername = $"M:{methodInfo.DeclaringType.FullName}.{methodInfo.Name}"; + var member = xdoc.Descendants("member") + .FirstOrDefault(m => m.Attribute("name").Value.ToString().Contains(membername));// 瀹氫綅鍒版柟娉曡妭鐐� + //.FirstOrDefault(m => m.Attribute("name")?.Value == $"M:{methodInfo.DeclaringType.FullName}.{methodInfo.Name}"); // 瀹氫綅鍒版柟娉曡妭鐐� + //if (member == null) return "Member not found in XML documentation."; // 妫�鏌ユ柟娉曟槸鍚﹀湪XML鏂囨。涓壘鍒� + //var summary = member?.Element("summary")?.Value ?? "No summary provided."; // 鑾峰彇鎽樿淇℃伅鎴栭粯璁ゅ�� + Methodremark = member?.Element("summary")?.Value.Replace("\n", "").Replace(" ", "") ?? methodInfo.Name; // 鑾峰彇鎽樿淇℃伅鎴栭粯璁ゅ�� + } + } + } + catch (Exception ex) + { - //{"BeginDate",beginDate }, - //{"ElapsedTime",(endDate - beginDate).TotalMilliseconds.ObjToInt() }, - //{"EndDate",endDate }, - //{"RequestParam",requestParameter }, - //{"ResponseParam",responseParameter }, - //{"Success",1 }, - //{"Url",context.Request.Path.Value??"" }, - //{"UserIP",context.GetUserIp() }, - //{"UserName","App.User?.Name" }, - //{"User_Id","App.User?.ID" } + } + #endregion + //鑾峰彇褰撳墠鐢ㄦ埛 + IUser user = App.User; + //鍒涘缓鏃ュ織瀵硅薄 + log = new + { + //璇锋眰寮�濮嬫椂闂� + BeginDate = logModel.RequestDate, + //璇锋眰缁撴潫鏃堕棿 + EndDate = DateTime.Now, + //璇锋眰鍙傛暟 + RequestParam = requestParameter, + //鍝嶅簲鍙傛暟 + ResponseParam = responseParameter, + //鏂规硶鍚嶇О + MethodName = MethodName, + //鏂规硶鎻忚堪 + Methodremark= Methodremark, + //鍝嶅簲鐘舵�� + Success = LogStatusEnum.Success.ObjToInt(), + //璇锋眰URL + Url = context.Request.Scheme + "://" + context.Request.Host + context.Request.PathBase + context.Request.Path, + //瀹㈡埛绔疘P + UserIP = GetClientIP(context)?.Replace("::ffff:", "").Replace("::1", "127.0.0.1"), + //鐢ㄦ埛ID + UserId = user.UserId, + //鐢ㄦ埛鍚� + UserName = user.UserName }; - - - SqlSugarClient sqlSugarClient = DBContext.GetCustomDB(DBContext.GetConnectionConfig()); - sqlSugarClient.Insertable(dic).AS("Sys_Log").ExecuteCommand(); } - catch (Exception ex) + catch (Exception exception) { - + //濡傛灉鍙戠敓寮傚父锛屽垯鍒涘缓鏃ュ織瀵硅薄 + log = log ?? new + { + //璇锋眰寮�濮嬫椂闂� + BeginDate = DateTime.Now, + //璇锋眰缁撴潫鏃堕棿 + EndDate = DateTime.Now, + //璇锋眰鍙傛暟 + RequestParam = requestParameter, + //鍝嶅簲鍙傛暟 + ResponseParam = responseParameter, + //鏂规硶鍚嶇О + MethodName = MethodName, + //鏂规硶鎻忚堪 + Methodremark = Methodremark, + //鍝嶅簲鐘舵�� + Success = LogStatusEnum.Error.ObjToInt(), + }; } + //娣诲姞绯荤粺鏃ュ織 + loggerQueueData.Enqueue(log); } - } - public enum LoggerStatus - { - Success = 1, - Error = 2, - Info = 3 + public static void Add(string url, string requestParameter, string responseParameter, DateTime beginDate) + { + dynamic? log = null; + try + { + //鑾峰彇褰撳墠鐢ㄦ埛 + IUser? user = App.User; + //鍒涘缓鏃ュ織瀵硅薄 + log = new + { + //璇锋眰寮�濮嬫椂闂� + BeginDate = beginDate, + //璇锋眰缁撴潫鏃堕棿 + EndDate = DateTime.Now, + //璇锋眰鍙傛暟 + RequestParam = requestParameter, + //鍝嶅簲鍙傛暟 + ResponseParam = responseParameter, + //璇锋眰URL + Url = url, + //瀹㈡埛绔疘P + UserIP = "", + //鐢ㄦ埛ID + UserId = user?.UserId, + //鐢ㄦ埛鍚� + UserName = user?.UserName + }; + } + catch (Exception exception) + { + //濡傛灉鍙戠敓寮傚父锛屽垯鍒涘缓鏃ュ織瀵硅薄 + log = log ?? new + { + //璇锋眰寮�濮嬫椂闂� + BeginDate = DateTime.Now, + //璇锋眰缁撴潫鏃堕棿 + EndDate = DateTime.Now, + //璇锋眰鍙傛暟 + RequestParam = requestParameter, + //鍝嶅簲鍙傛暟 + ResponseParam = responseParameter, + }; + } + //娣诲姞绯荤粺鏃ュ織 + loggerQueueData.Enqueue(log); + } + + 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; + } } } -- Gitblit v1.9.3