LogCleaner.cs 7.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204
  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. private string _logFilePath;
  18. /// <summary>
  19. /// LogCleaner 构造函数
  20. /// 启用SC参数
  21. /// "System.LogsSaveDays"
  22. /// "System.IsEnableCompressLogFileFunc"
  23. /// "System.SingleLogFileMaxSize"
  24. /// </summary>
  25. public LogCleaner()
  26. {
  27. if (SC.ContainsItem("System.LogsSaveDays"))
  28. {
  29. LogsSaveDays = SC.GetValue<int>("System.LogsSaveDays");
  30. }
  31. if (SC.ContainsItem("System.IsEnableCompressLogFileFunc"))
  32. {
  33. IsEnableCompressLogFileFunc = SC.GetValue<bool>("System.IsEnableCompressLogFileFunc");
  34. }
  35. if (SC.ContainsItem("System.SingleLogFileMaxSize"))
  36. {
  37. SingleLogFileMaxSize = SC.GetValue<int>("System.SingleLogFileMaxSize");
  38. }
  39. _logFilePath = SC.GetStringValue("System.LogFilePath");
  40. }
  41. /// <summary>
  42. /// LogCleaner 构造函数
  43. /// </summary>
  44. /// <param name="logsSaveDays">文件保存时间, 需设置≥7天</param>
  45. /// <param name="isEnableCompressLogFileFunc" >是否启用文件压缩功能</param>
  46. /// <param name="singleLogFileMaxSize">超过此大小的文件将会被压缩(以兆字节为单位), 需设置≥1兆</param>
  47. public LogCleaner(int logsSaveDays, bool isEnableCompressLogFileFunc, int singleLogFileMaxSize)
  48. {
  49. LogsSaveDays = logsSaveDays;
  50. IsEnableCompressLogFileFunc = isEnableCompressLogFileFunc;
  51. SingleLogFileMaxSize = singleLogFileMaxSize;
  52. }
  53. public LogCleaner(int logsSaveDays)
  54. {
  55. LogsSaveDays = logsSaveDays;
  56. }
  57. public bool IsEnableCompressLogFileFunc { get; set; }
  58. private int _logsSaveDays = 60;
  59. public int LogsSaveDays
  60. {
  61. get { return _logsSaveDays < 7 ? 7 : _logsSaveDays; }
  62. set { _logsSaveDays = value; }
  63. }
  64. private int _singleFileMaxSize = 100;
  65. public int SingleLogFileMaxSize
  66. {
  67. get { return _singleFileMaxSize < 1 ? 1 : _singleFileMaxSize; }
  68. set { _singleFileMaxSize = value; }
  69. }
  70. public void Run()
  71. {
  72. //1天运行一次,删除一个月之前的 log文件
  73. _threadDeleteLogs = new PeriodicJob(1000 * 60 * 60 * 24, OnDeleteLog, "DeleteLog Thread", true);
  74. }
  75. bool OnDeleteLog()
  76. {
  77. try
  78. {
  79. string path = PathManager.IsValidDirectoryPath(_logFilePath) ? _logFilePath : PathManager.GetLogDir();
  80. FileInfo[] fileInfos;
  81. DirectoryInfo curFolderInfo = new DirectoryInfo(path);
  82. fileInfos = curFolderInfo.GetFiles();
  83. foreach (FileInfo info in fileInfos)
  84. {
  85. if (info.Name.Contains("Log")||info.Name.Contains("log") || info.Extension == ".log")
  86. {
  87. DateTime lastWriteTime = DateTime.Parse(info.LastWriteTime.ToShortDateString());
  88. DateTime intervalTime = DateTime.Now.AddDays(-LogsSaveDays);// DateTime.Parse(DateTime.Now.AddMonths(-1).ToShortDateString());
  89. if (lastWriteTime < intervalTime)
  90. {
  91. File.Delete(info.FullName);
  92. LOG.Write(string.Format("delete log successfully,logName:{0}", info.Name));
  93. }
  94. else if (IsEnableCompressLogFileFunc && info.Length > SingleLogFileMaxSize * 1024 * 1024 && lastWriteTime < DateTime.Now.AddDays(-1) && info.Extension != ".zip")
  95. {
  96. if (CompressFile(info.FullName, info.FullName + ".zip"))
  97. {
  98. File.Delete(info.FullName);
  99. LOG.Write(string.Format("delete log successfully,logName:{0}", info.Name));
  100. }
  101. }
  102. }
  103. }
  104. }
  105. catch (Exception ex)
  106. {
  107. LOG.Write(ex);
  108. }
  109. return true;
  110. }
  111. public void Stop()
  112. {
  113. _threadDeleteLogs?.Stop();
  114. }
  115. /// <summary>
  116. /// 压缩文件/文件夹
  117. /// </summary>
  118. /// <param name="filePath">需要压缩的文件/文件夹路径</param>
  119. /// <param name="zipPath">压缩文件路径(zip后缀)</param>
  120. /// <param name="password">密码</param>
  121. /// <param name="filterExtenList">需要过滤的文件后缀名</param>
  122. private bool CompressFile(string filePath, string zipPath, string password = "", List<string> filterExtenList = null)
  123. {
  124. try
  125. {
  126. using (ZipFile zip = new ZipFile(Encoding.UTF8))
  127. {
  128. if (!string.IsNullOrWhiteSpace(password))
  129. {
  130. zip.Password = password;
  131. }
  132. if (Directory.Exists(filePath))
  133. {
  134. if (filterExtenList == null)
  135. zip.AddDirectory(filePath);
  136. else
  137. AddDirectory(zip, filePath, filePath, filterExtenList);
  138. }
  139. else if (File.Exists(filePath))
  140. {
  141. zip.AddFile(filePath, "");
  142. }
  143. zip.Save(zipPath);
  144. return true;
  145. }
  146. }
  147. catch (Exception ex)
  148. {
  149. LOG.Write(ex);
  150. }
  151. return false;
  152. }
  153. /// <summary>
  154. /// 添加文件夹
  155. /// </summary>
  156. /// <param name="zip">ZipFile对象</param>
  157. /// <param name="dirPath">需要压缩的文件夹路径</param>
  158. /// <param name="rootPath">根目录路径</param>
  159. /// <param name="filterExtenList">需要过滤的文件后缀名</param>
  160. private void AddDirectory(ZipFile zip, string dirPath, string rootPath, List<string> filterExtenList)
  161. {
  162. var files = Directory.GetFiles(dirPath);
  163. for (int i = 0; i < files.Length; i++)
  164. {
  165. if (filterExtenList == null || (filterExtenList != null && !filterExtenList.Any(d => Path.GetExtension(files[i]).ToLower() == d.ToLower())))
  166. {
  167. string relativePath = Path.GetFullPath(dirPath).Replace(Path.GetFullPath(rootPath), "");
  168. zip.AddFile(files[i], relativePath);
  169. }
  170. }
  171. var dirs = Directory.GetDirectories(dirPath);
  172. for (int i = 0; i < dirs.Length; i++)
  173. {
  174. AddDirectory(zip, dirs[i], rootPath, filterExtenList);
  175. }
  176. }
  177. ~LogCleaner()
  178. {
  179. Stop();
  180. }
  181. }
  182. }