LogCleaner.cs 7.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214
  1. using Aitex.Common.Util;
  2. using Aitex.Core.RT.Log;
  3. using Aitex.Core.RT.SCCore;
  4. using Aitex.Core.Util;
  5. using Ionic.Zip;
  6. using System;
  7. using System.Collections.Generic;
  8. using System.IO;
  9. using System.Linq;
  10. using System.Text;
  11. using System.Threading.Tasks;
  12. namespace MECF.Framework.Common.Log
  13. {
  14. public class LogCleaner
  15. {
  16. PeriodicJob _threadDeleteLogs;
  17. /// <summary>
  18. /// LogCleaner 构造函数
  19. /// 启用SC参数
  20. /// "System.LogsSaveDays"
  21. /// "System.IsEnableCompressLogFileFunc"
  22. /// "System.SingleLogFileMaxSize"
  23. /// </summary>
  24. public LogCleaner()
  25. {
  26. if (SC.ContainsItem("System.LogsSaveDays"))
  27. {
  28. LogsSaveDays = SC.GetValue<int>("System.LogsSaveDays");
  29. }
  30. if (SC.ContainsItem("System.IsEnableCompressLogFileFunc"))
  31. {
  32. IsEnableCompressLogFileFunc = SC.GetValue<bool>("System.IsEnableCompressLogFileFunc");
  33. }
  34. if (SC.ContainsItem("System.SingleLogFileMaxSize"))
  35. {
  36. SingleLogFileMaxSize = SC.GetValue<int>("System.SingleLogFileMaxSize");
  37. }
  38. }
  39. /// <summary>
  40. /// LogCleaner 构造函数
  41. /// </summary>
  42. /// <param name="logsSaveDays">文件保存时间, 需设置≥7天</param>
  43. /// <param name="isEnableCompressLogFileFunc" >是否启用文件压缩功能</param>
  44. /// <param name="singleLogFileMaxSize">超过此大小的文件将会被压缩(以兆字节为单位), 需设置≥1兆</param>
  45. public LogCleaner(int logsSaveDays, bool isEnableCompressLogFileFunc, int singleLogFileMaxSize)
  46. {
  47. LogsSaveDays = logsSaveDays;
  48. IsEnableCompressLogFileFunc = isEnableCompressLogFileFunc;
  49. SingleLogFileMaxSize = singleLogFileMaxSize;
  50. }
  51. public LogCleaner(int logsSaveDays)
  52. {
  53. LogsSaveDays = logsSaveDays;
  54. }
  55. public bool IsEnableCompressLogFileFunc { get; set; }
  56. private int _logsSaveDays = 60;
  57. public int LogsSaveDays
  58. {
  59. get { return _logsSaveDays < 7 ? 7 : _logsSaveDays; }
  60. set { _logsSaveDays = value; }
  61. }
  62. private int _singleFileMaxSize = 100;
  63. public int SingleLogFileMaxSize
  64. {
  65. get { return _singleFileMaxSize < 1 ? 1 : _singleFileMaxSize; }
  66. set { _singleFileMaxSize = value; }
  67. }
  68. public void Run()
  69. {
  70. //1天运行一次,删除一个月之前的 log文件
  71. _threadDeleteLogs = new PeriodicJob(1000 * 60 * 60 * 24, OnDeleteLog, "DeleteLog Thread", true);
  72. }
  73. bool OnDeleteLog()
  74. {
  75. try
  76. {
  77. if (SC.ContainsItem("System.LogsSaveDays"))
  78. {
  79. LogsSaveDays = SC.GetValue<int>("System.LogsSaveDays");
  80. }
  81. if (SC.ContainsItem("System.IsEnableCompressLogFileFunc"))
  82. {
  83. IsEnableCompressLogFileFunc = SC.GetValue<bool>("System.IsEnableCompressLogFileFunc");
  84. }
  85. if (SC.ContainsItem("System.SingleLogFileMaxSize"))
  86. {
  87. SingleLogFileMaxSize = SC.GetValue<int>("System.SingleLogFileMaxSize");
  88. }
  89. string path = PathManager.GetLogDir();
  90. FileInfo[] fileInfos;
  91. DirectoryInfo curFolderInfo = new DirectoryInfo(path);
  92. fileInfos = curFolderInfo.GetFiles();
  93. foreach (FileInfo info in fileInfos)
  94. {
  95. if (info.Name.Contains("Log") || info.Name.Contains("log") || info.Name.Contains("FabConnect") || info.Extension == ".log")
  96. {
  97. DateTime lastWriteTime = DateTime.Parse(info.LastWriteTime.ToShortDateString());
  98. DateTime intervalTime = DateTime.Now.AddDays(-LogsSaveDays);// DateTime.Parse(DateTime.Now.AddMonths(-1).ToShortDateString());
  99. if (lastWriteTime < intervalTime)
  100. {
  101. File.Delete(info.FullName);
  102. LOG.Write(string.Format("delete log successfully,logName:{0}", info.Name));
  103. }
  104. else if (IsEnableCompressLogFileFunc && info.Length > SingleLogFileMaxSize * 1024 * 1024 && lastWriteTime < DateTime.Now.AddDays(-1) && info.Extension != ".zip")
  105. {
  106. if (CompressFile(info.FullName, info.FullName + ".zip"))
  107. {
  108. File.Delete(info.FullName);
  109. LOG.Write(string.Format("delete log successfully,logName:{0}", info.Name));
  110. }
  111. }
  112. }
  113. }
  114. }
  115. catch (Exception ex)
  116. {
  117. LOG.Write(ex);
  118. }
  119. return true;
  120. }
  121. public void Stop()
  122. {
  123. _threadDeleteLogs?.Stop();
  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.Write(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. ~LogCleaner()
  188. {
  189. Stop();
  190. }
  191. }
  192. }