LogManager.cs 7.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216
  1. using System;
  2. using System.Collections.Generic;
  3. using System.IO;
  4. using System.Linq;
  5. using System.Text;
  6. using System.Timers;
  7. using Aitex.Core.RT.SCCore;
  8. using Ionic.Zip;
  9. namespace Aitex.Core.RT.Log
  10. {
  11. public class LogManager : ICommonLog
  12. {
  13. public const int MaxLogsMonth = 3;
  14. public static readonly log4net.ILog loginfo = log4net.LogManager.GetLogger("fileAppender");
  15. private static Timer deleteTimer;//定义定时器,定时删除log
  16. private int _logsSaveDays;
  17. private bool _isEnableCompressLogFile;
  18. public void Initialize()
  19. {
  20. if (SC.ContainsItem("System.LogsSaveDays"))
  21. {
  22. _logsSaveDays = SC.GetValue<int>("System.LogsSaveDays");
  23. }
  24. if (SC.ContainsItem("System.IsEnableCompressLogFile"))
  25. {
  26. _isEnableCompressLogFile = SC.GetValue<bool>("System.IsEnableCompressLogFile");
  27. }
  28. deleteTimer = new Timer(1);
  29. deleteTimer.Elapsed += OnDeleteLog;
  30. deleteTimer.AutoReset = true;
  31. deleteTimer.Enabled = true;
  32. LOG.InnerLogger = this;
  33. }
  34. public void Debug(string message)
  35. {
  36. loginfo.Debug(message);
  37. }
  38. public void Info(string message)
  39. {
  40. loginfo.Info(message);
  41. }
  42. public void Warning(string message)
  43. {
  44. loginfo.Warn(message);
  45. }
  46. public void Error(string message)
  47. {
  48. loginfo.Error(message);
  49. }
  50. /// <summary>
  51. /// 定期删除log
  52. /// </summary>
  53. /// <returns></returns>
  54. void OnDeleteLog(Object source, ElapsedEventArgs e)
  55. {
  56. if (deleteTimer.Interval == 1)
  57. {
  58. deleteTimer.Interval = 60 * 1000;//每隔1分钟删除
  59. }
  60. else if (deleteTimer.Interval == 60 * 1000)
  61. {
  62. if (DateTime.Now.Hour == 0 && DateTime.Now.Minute == 5)//下一次是0点10分
  63. {
  64. deleteTimer.Interval = 60 * 60 * 1000;
  65. }
  66. else
  67. {
  68. return;
  69. }
  70. }
  71. else if (deleteTimer.Interval == 60 * 60 * 1000)
  72. {
  73. if (DateTime.Now.Hour != 0)
  74. {
  75. return;
  76. }
  77. }
  78. try
  79. {
  80. string path = string.Format(@"{0}", "Logs");
  81. FileInfo[] fileInfos;
  82. DirectoryInfo curFolderInfo = new DirectoryInfo(path);
  83. fileInfos = curFolderInfo.GetFiles();
  84. List<string> deleteLst = new List<string>();
  85. foreach (FileInfo info in fileInfos)
  86. {
  87. if (info.Extension == ".log" || info.Extension == ".txt" || info.Name.Contains("log"))
  88. {
  89. DateTime lastWriteTime = DateTime.Parse(info.LastWriteTime.ToShortDateString());
  90. if (_logsSaveDays != 0)
  91. {
  92. DateTime intervalTime = DateTime.Now.AddDays(-_logsSaveDays);
  93. if (lastWriteTime < intervalTime)
  94. {
  95. File.Delete(info.FullName);
  96. continue;
  97. }
  98. }
  99. if (_isEnableCompressLogFile && info.Extension != ".zip" && lastWriteTime < DateTime.Now.AddDays(-1))
  100. {
  101. if (CompressFile(info.FullName, $"{curFolderInfo.FullName}//{info.Name}.zip"))
  102. {
  103. deleteLst.Add(info.FullName);
  104. }
  105. }
  106. }
  107. foreach (string item in deleteLst)
  108. {
  109. try
  110. {
  111. File.Delete(item);
  112. LOG.WriteBackgroundLog(eEvent.INFO_WINRESOURCE, "System", $"delete log successfully,logName:{item}");
  113. }
  114. catch
  115. {
  116. }
  117. }
  118. }
  119. }
  120. catch(Exception ex)
  121. {
  122. LOG.WriteExeption(ex);
  123. }
  124. }
  125. /// <summary>
  126. /// 压缩文件/文件夹
  127. /// </summary>
  128. /// <param name="filePath">需要压缩的文件/文件夹路径</param>
  129. /// <param name="zipPath">压缩文件路径(zip后缀)</param>
  130. /// <param name="password">密码</param>
  131. /// <param name="filterExtenList">需要过滤的文件后缀名</param>
  132. private bool CompressFile(string filePath, string zipPath, string password = "", List<string> filterExtenList = null)
  133. {
  134. try
  135. {
  136. using (ZipFile zip = new ZipFile(Encoding.UTF8))
  137. {
  138. if (!string.IsNullOrWhiteSpace(password))
  139. {
  140. zip.Password = password;
  141. }
  142. if (Directory.Exists(filePath))
  143. {
  144. if (filterExtenList == null)
  145. zip.AddDirectory(filePath);
  146. else
  147. AddDirectory(zip, filePath, filePath, filterExtenList);
  148. }
  149. else if (File.Exists(filePath))
  150. {
  151. zip.AddFile(filePath, "");
  152. }
  153. zip.Save(zipPath);
  154. return true;
  155. }
  156. }
  157. catch (Exception ex)
  158. {
  159. LOG.WriteExeption(ex);
  160. }
  161. return false;
  162. }
  163. /// <summary>
  164. /// 添加文件夹
  165. /// </summary>
  166. /// <param name="zip">ZipFile对象</param>
  167. /// <param name="dirPath">需要压缩的文件夹路径</param>
  168. /// <param name="rootPath">根目录路径</param>
  169. /// <param name="filterExtenList">需要过滤的文件后缀名</param>
  170. private void AddDirectory(ZipFile zip, string dirPath, string rootPath, List<string> filterExtenList)
  171. {
  172. var files = Directory.GetFiles(dirPath);
  173. for (int i = 0; i < files.Length; i++)
  174. {
  175. if (filterExtenList == null || (filterExtenList != null && !filterExtenList.Any(d => Path.GetExtension(files[i]).ToLower() == d.ToLower())))
  176. {
  177. string relativePath = Path.GetFullPath(dirPath).Replace(Path.GetFullPath(rootPath), "");
  178. zip.AddFile(files[i], relativePath);
  179. }
  180. }
  181. var dirs = Directory.GetDirectories(dirPath);
  182. for (int i = 0; i < dirs.Length; i++)
  183. {
  184. AddDirectory(zip, dirs[i], rootPath, filterExtenList);
  185. }
  186. }
  187. public void Terminate()
  188. {
  189. try
  190. {
  191. if (deleteTimer != null)
  192. {
  193. deleteTimer.Enabled = false;
  194. }
  195. }
  196. catch (Exception ex)
  197. {
  198. System.Diagnostics.Trace.WriteLine(ex.Message);
  199. }
  200. }
  201. }
  202. }