LogCleaner.cs 7.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202
  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. string path = PathManager.GetLogDir();
  78. FileInfo[] fileInfos;
  79. DirectoryInfo curFolderInfo = new DirectoryInfo(path);
  80. fileInfos = curFolderInfo.GetFiles();
  81. foreach (FileInfo info in fileInfos)
  82. {
  83. if (info.Name.Contains("Log")||info.Name.Contains("log") || info.Extension == ".log")
  84. {
  85. DateTime lastWriteTime = DateTime.Parse(info.LastWriteTime.ToShortDateString());
  86. DateTime intervalTime = DateTime.Now.AddDays(-LogsSaveDays);// DateTime.Parse(DateTime.Now.AddMonths(-1).ToShortDateString());
  87. if (lastWriteTime < intervalTime)
  88. {
  89. File.Delete(info.FullName);
  90. LOG.Write(string.Format("delete log successfully,logName:{0}", info.Name));
  91. }
  92. else if (IsEnableCompressLogFileFunc && info.Length > SingleLogFileMaxSize * 1024 * 1024 && lastWriteTime < DateTime.Now.AddDays(-1) && info.Extension != ".zip")
  93. {
  94. if (CompressFile(info.FullName, info.FullName + ".zip"))
  95. {
  96. File.Delete(info.FullName);
  97. LOG.Write(string.Format("delete log successfully,logName:{0}", info.Name));
  98. }
  99. }
  100. }
  101. }
  102. }
  103. catch (Exception ex)
  104. {
  105. LOG.Write(ex);
  106. }
  107. return true;
  108. }
  109. public void Stop()
  110. {
  111. _threadDeleteLogs?.Stop();
  112. }
  113. /// <summary>
  114. /// 压缩文件/文件夹
  115. /// </summary>
  116. /// <param name="filePath">需要压缩的文件/文件夹路径</param>
  117. /// <param name="zipPath">压缩文件路径(zip后缀)</param>
  118. /// <param name="password">密码</param>
  119. /// <param name="filterExtenList">需要过滤的文件后缀名</param>
  120. private bool CompressFile(string filePath, string zipPath, string password = "", List<string> filterExtenList = null)
  121. {
  122. try
  123. {
  124. using (ZipFile zip = new ZipFile(Encoding.UTF8))
  125. {
  126. if (!string.IsNullOrWhiteSpace(password))
  127. {
  128. zip.Password = password;
  129. }
  130. if (Directory.Exists(filePath))
  131. {
  132. if (filterExtenList == null)
  133. zip.AddDirectory(filePath);
  134. else
  135. AddDirectory(zip, filePath, filePath, filterExtenList);
  136. }
  137. else if (File.Exists(filePath))
  138. {
  139. zip.AddFile(filePath, "");
  140. }
  141. zip.Save(zipPath);
  142. return true;
  143. }
  144. }
  145. catch (Exception ex)
  146. {
  147. LOG.Write(ex);
  148. }
  149. return false;
  150. }
  151. /// <summary>
  152. /// 添加文件夹
  153. /// </summary>
  154. /// <param name="zip">ZipFile对象</param>
  155. /// <param name="dirPath">需要压缩的文件夹路径</param>
  156. /// <param name="rootPath">根目录路径</param>
  157. /// <param name="filterExtenList">需要过滤的文件后缀名</param>
  158. private void AddDirectory(ZipFile zip, string dirPath, string rootPath, List<string> filterExtenList)
  159. {
  160. var files = Directory.GetFiles(dirPath);
  161. for (int i = 0; i < files.Length; i++)
  162. {
  163. if (filterExtenList == null || (filterExtenList != null && !filterExtenList.Any(d => Path.GetExtension(files[i]).ToLower() == d.ToLower())))
  164. {
  165. string relativePath = Path.GetFullPath(dirPath).Replace(Path.GetFullPath(rootPath), "");
  166. zip.AddFile(files[i], relativePath);
  167. }
  168. }
  169. var dirs = Directory.GetDirectories(dirPath);
  170. for (int i = 0; i < dirs.Length; i++)
  171. {
  172. AddDirectory(zip, dirs[i], rootPath, filterExtenList);
  173. }
  174. }
  175. ~LogCleaner()
  176. {
  177. Stop();
  178. }
  179. }
  180. }