LogManager.cs 7.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203
  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 != 10)//下一次是0点10分钟
  63. {
  64. return;
  65. }
  66. else
  67. {
  68. deleteTimer.Interval = 60 * 60 * 1000;
  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. foreach (FileInfo info in fileInfos)
  85. {
  86. if (info.Extension == ".log" || info.Extension == ".txt" || info.Name.Contains("log"))
  87. {
  88. DateTime lastWriteTime = DateTime.Parse(info.LastWriteTime.ToShortDateString());
  89. if (_logsSaveDays != 0)
  90. {
  91. DateTime intervalTime = DateTime.Now.AddDays(-_logsSaveDays);
  92. if (lastWriteTime < intervalTime)
  93. {
  94. File.Delete(info.FullName);
  95. continue;
  96. }
  97. }
  98. if (_isEnableCompressLogFile && info.Extension != ".zip" && lastWriteTime < DateTime.Now.AddDays(-1))
  99. {
  100. if (CompressFile(info.FullName, $"{curFolderInfo.FullName}//{info.Name}.zip"))
  101. {
  102. File.Delete(info.FullName);
  103. LOG.WriteBackgroundLog(eEvent.INFO_WINRESOURCE, "System", $"delete log successfully,logName:{info.Name}");
  104. }
  105. }
  106. }
  107. }
  108. }
  109. catch(Exception ex)
  110. {
  111. LOG.WriteExeption(ex);
  112. }
  113. }
  114. /// <summary>
  115. /// 压缩文件/文件夹
  116. /// </summary>
  117. /// <param name="filePath">需要压缩的文件/文件夹路径</param>
  118. /// <param name="zipPath">压缩文件路径(zip后缀)</param>
  119. /// <param name="password">密码</param>
  120. /// <param name="filterExtenList">需要过滤的文件后缀名</param>
  121. private bool CompressFile(string filePath, string zipPath, string password = "", List<string> filterExtenList = null)
  122. {
  123. try
  124. {
  125. using (ZipFile zip = new ZipFile(Encoding.UTF8))
  126. {
  127. if (!string.IsNullOrWhiteSpace(password))
  128. {
  129. zip.Password = password;
  130. }
  131. if (Directory.Exists(filePath))
  132. {
  133. if (filterExtenList == null)
  134. zip.AddDirectory(filePath);
  135. else
  136. AddDirectory(zip, filePath, filePath, filterExtenList);
  137. }
  138. else if (File.Exists(filePath))
  139. {
  140. zip.AddFile(filePath, "");
  141. }
  142. zip.Save(zipPath);
  143. return true;
  144. }
  145. }
  146. catch (Exception ex)
  147. {
  148. LOG.WriteExeption(ex);
  149. }
  150. return false;
  151. }
  152. /// <summary>
  153. /// 添加文件夹
  154. /// </summary>
  155. /// <param name="zip">ZipFile对象</param>
  156. /// <param name="dirPath">需要压缩的文件夹路径</param>
  157. /// <param name="rootPath">根目录路径</param>
  158. /// <param name="filterExtenList">需要过滤的文件后缀名</param>
  159. private void AddDirectory(ZipFile zip, string dirPath, string rootPath, List<string> filterExtenList)
  160. {
  161. var files = Directory.GetFiles(dirPath);
  162. for (int i = 0; i < files.Length; i++)
  163. {
  164. if (filterExtenList == null || (filterExtenList != null && !filterExtenList.Any(d => Path.GetExtension(files[i]).ToLower() == d.ToLower())))
  165. {
  166. string relativePath = Path.GetFullPath(dirPath).Replace(Path.GetFullPath(rootPath), "");
  167. zip.AddFile(files[i], relativePath);
  168. }
  169. }
  170. var dirs = Directory.GetDirectories(dirPath);
  171. for (int i = 0; i < dirs.Length; i++)
  172. {
  173. AddDirectory(zip, dirs[i], rootPath, filterExtenList);
  174. }
  175. }
  176. public void Terminate()
  177. {
  178. try
  179. {
  180. if (deleteTimer != null)
  181. {
  182. deleteTimer.Enabled = false;
  183. }
  184. }
  185. catch (Exception ex)
  186. {
  187. System.Diagnostics.Trace.WriteLine(ex.Message);
  188. }
  189. }
  190. }
  191. }