From 695571c6009ecbc12e7d4a4fb147df7967a1260e Mon Sep 17 00:00:00 2001
From: wangxinhui <wangxinhui@hnkhzn.com>
Date: 星期一, 07 七月 2025 20:21:19 +0800
Subject: [PATCH] Merge branch 'master' of http://115.159.85.185:8098/r/MeiRuiAn/HuaiAn
---
代码管理/WMS/WIDESEA_WMSServer/WIDESEA_Core/LogHelper/Logger.cs | 321 ++++++++++++++++++++++++++++++++++-------------------
1 files changed, 207 insertions(+), 114 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..d833379 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,9 +1,9 @@
-锘�
-using Microsoft.AspNetCore.Http;
-using Newtonsoft.Json;
+锘縰sing Microsoft.AspNetCore.Http;
using SqlSugar;
using System;
+using System.Collections.Concurrent;
using System.Collections.Generic;
+using System.Data;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
@@ -14,145 +14,238 @@
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;
+ // 灏唕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("LogType", typeof(string));
+ //queueTable.Columns.Add("ExceptionInfo", 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;
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;
}
+ //濡傛灉璇锋眰鏂规硶涓篛PTIONS锛屽垯杩斿洖
+ if (context.Request.Method == "OPTIONS") return;
+ //鑾峰彇RequestLogModel瀹炰緥
+ RequestLogModel logModel = (context.RequestServices.GetService(typeof(RequestLogModel)) as RequestLogModel) ?? new RequestLogModel { RequestDate = DateTime.Now };
- Dictionary<string, object> dic = new Dictionary<string, object>
+ //鑾峰彇褰撳墠鐢ㄦ埛
+ IUser user = App.User;
+ //鍒涘缓鏃ュ織瀵硅薄
+ log = new
{
- {"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" }
-
- //{"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" }
+ //璇锋眰寮�濮嬫椂闂�
+ BeginDate = logModel.RequestDate,
+ //璇锋眰缁撴潫鏃堕棿
+ EndDate = DateTime.Now,
+ //璇锋眰鍙傛暟
+ RequestParam = requestParameter,
+ //鍝嶅簲鍙傛暟
+ ResponseParam = responseParameter,
+ //璇锋眰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,
+ };
}
+ //娣诲姞绯荤粺鏃ュ織
+ 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