| | |
| | |  |
| | | using Microsoft.AspNetCore.Http; |
| | | using Newtonsoft.Json; |
| | | using 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çBeginDate为空æè
BeginDateç年份å°äº2010ï¼åå°BeginDate设置为å½åæ¶é´ |
| | | if (log.BeginDate == null || log.BeginDate?.Year < 2010) |
| | | { |
| | | log.BeginDate = DateTime.Now; |
| | | } |
| | | // 妿logçEndDate为空ï¼åå°EndDate设置为å½åæ¶é´ |
| | | if (log.EndDate == null) |
| | | { |
| | | log.EndDate = DateTime.Now; |
| | | } |
| | | // row["Id"] = log.Id; |
| | | // å°RequestParamä¸çæ¢è¡ç¬¦æ¿æ¢ä¸ºç©ºå符串 |
| | | row["RequestParam"] = log.RequestParam?.Replace("\r\n", "").Replace("\n", ""); |
| | | // å°ResponseParamä¸çæ¢è¡ç¬¦æ¿æ¢ä¸ºç©ºå符串 |
| | | row["ResponseParam"] = log.ResponseParam?.Replace("\r\n", "").Replace("\n", ""); |
| | | row["Success"] = log.Success ?? -1; |
| | | // å°BeginDate设置为logçBeginDate |
| | | row["BeginDate"] = log.BeginDate; |
| | | // å°EndDate设置为logçEndDate |
| | | row["EndDate"] = log.EndDate; |
| | | // 计ç®ElapsedTimeï¼å³EndDateåå»BeginDateçæ¯«ç§æ° |
| | | row["ElapsedTime"] = ((DateTime)log.EndDate - (DateTime)log.BeginDate).TotalMilliseconds; |
| | | // å°UserIP设置为logçUserIP |
| | | row["UserIP"] = log.UserIP; |
| | | // å°Url设置为logçUrl |
| | | row["Url"] = log.Url; |
| | | // 妿logçUserId为空ï¼åå°UserId设置为-1ï¼å¦å设置为logçUserId |
| | | row["UserId"] = log.UserId ?? -1; |
| | | // å°UserName设置为logçUserName |
| | | row["UserName"] = log.UserName; |
| | | row["MethodName"] = log.MethodName; |
| | | row["Methodremark"] = log.Methodremark; |
| | | // å°rowæ·»å å°queueTableä¸ |
| | | 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> |
| | | //å¦æè¯·æ±æ¹æ³ä¸ºOPTIONSï¼åè¿å |
| | | 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, |
| | | //客æ·ç«¯IP |
| | | 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, |
| | | //客æ·ç«¯IP |
| | | 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) |
| | | { |
| | | // è·å请æ±å¤´ä¸çX-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; |
| | | } |
| | | } |
| | | } |