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