记录日志文件 日志文件的内容以Json格式保存到txt文件中
封装一个方法,传不同的参数,记录不同类型的日志文件,并将大的日志内容,以Json的格式,保存值txt日志文件
1.记录操作日志
1 //记录操作日志 2 var KeyWord = "导入->编辑预算"; 3 new LogService(AccountId).CreateBudgetLog(Common.JsonHelper.ObjToJson(dbBudget), Common.JsonHelper.ObjToJson(budget), dbBudget.ID, dbBudget.BudgetCode, KeyWord, Enum_OperateLog_Type.Budget, Enum_OperateLog_CRUDType.UpdateS);
2.封装好的记录日志的接口
1 public bool CreateBudgetLog(string Oldjson, string Newjson, int ID, string Code, string KeyWord, Enum_OperateLog_Type Type, Enum_OperateLog_CRUDType CRUDType) 2 { 3 try 4 { 5 var dbUserInfo = this.GetObject(new UserInfo { ID = AccountId }) ?? new UserInfo(); 6 //记录日志 7 var operateLog = new OperateLog() 8 { 9 Created = DateTime.Now, 10 CreatedBy = AccountId, 11 IsDeleted = false, 12 Sn = Guid.NewGuid(), 13 LogID = ID, 14 LogCode = Code, 15 Title = KeyWord, 16 Type = Type.GetHashCode(), 17 CRUDType = CRUDType.GetHashCode(), 18 CreatedName = dbUserInfo.Name, 19 CreatedEmail = dbUserInfo.Email 20 }; 21 var FileUrl = string.Empty; 22 if (Type == Enum_OperateLog_Type.Budget) 23 { 24 FileUrl = "Budget_Log"; 25 } 26 else if (Type == Enum_OperateLog_Type.IO) 27 { 28 FileUrl = "IO_Log"; 29 } 30 else if (Type == Enum_OperateLog_Type.BaseExam) 31 { 32 FileUrl = "BaseExam_Log"; 33 } 34 else 35 { 36 FileUrl = "Operate_Log"; 37 } 38 39 //写入本地文件 40 var sitepath = ConfigHelper.Get("SitePath"); 41 var fileDir = $"\\Operate_Log\\{FileUrl}\\{DateTime.Now.ToString("yyyyMMdd")}\\"; 42 DirHelper.CheckFolder(sitepath + fileDir); 43 var fileUrl = sitepath + fileDir + Code + "_" + operateLog.Sn + ".txt"; 44 FileHelper.WriteFile(fileUrl, Oldjson + "\r\n" + Newjson); 45 operateLog.FileURL = fileUrl; 46 this.Create(operateLog); 47 48 return true; 49 } 50 catch (Exception) 51 { 52 53 throw; 54 } 55 56 }
3. FileHelper.WriteFile(fileUrl, Oldjson + "\r\n" + Newjson);
将对应Json写入指定文件
1 /// <summary> 2 /// 将字符串写入到指定文件 3 /// </summary> 4 /// <param name="filePath"></param> 5 /// <param name="fileContent"></param> 6 /// <returns></returns> 7 public static bool WriteFile(string filePath, string fileContent) 8 { 9 FileHelper.WriteFile(filePath, System.Text.Encoding.UTF8.GetBytes(fileContent)); 10 return true; 11 }
1 /// <summary> 2 /// 将字节写入到指定文件 3 /// </summary> 4 /// <param name="filePath"></param> 5 /// <param name="fileContent"></param> 6 public static void WriteFile(string filePath, byte[] fileContent) 7 { 8 var dirPath = filePath.Substring(0, filePath.LastIndexOf("\\")); 9 if (!Directory.Exists(dirPath)) 10 { 11 Directory.CreateDirectory(dirPath); 12 } 13 using (var fs = File.Create(filePath)) 14 { 15 fs.Write(fileContent, 0, fileContent.Length); 16 fs.Flush(); 17 } 18 }