LogManager.cs 2.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107
  1. using Aitex.Common.Util;
  2. using Aitex.Core.RT.SCCore;
  3. using System;
  4. using System.IO;
  5. using System.Timers;
  6. namespace Aitex.Core.RT.Log
  7. {
  8. public class LogManager : ICommonLog
  9. {
  10. public const int MaxLogsMonth = 3;
  11. public static readonly log4net.ILog loginfo = log4net.LogManager.GetLogger("fileAppender");
  12. private static Timer deleteTimer;//定义定时器,定时删除log
  13. private int logsDays = 7;
  14. public int LogsDays
  15. {
  16. get { return logsDays < 7 ? 7 : logsDays; }
  17. set
  18. {
  19. logsDays = value;
  20. }
  21. }
  22. public void Initialize()
  23. {
  24. deleteTimer = new Timer(1);
  25. deleteTimer.Elapsed += OnDeleteLog;
  26. deleteTimer.AutoReset = true;
  27. deleteTimer.Enabled = true;
  28. LOG.InnerLogger = this;
  29. LogsDays = SC.GetValue<int>($"System.LogsSaveDays");
  30. }
  31. public void Debug(string message)
  32. {
  33. loginfo.Debug(message);
  34. }
  35. public void Info(string message)
  36. {
  37. loginfo.Info(message);
  38. }
  39. public void Warning(string message)
  40. {
  41. loginfo.Warn(message);
  42. }
  43. public void Error(string message)
  44. {
  45. loginfo.Error(message);
  46. }
  47. /// <summary>
  48. /// 定期删除log
  49. /// </summary>
  50. /// <returns></returns>
  51. void OnDeleteLog(Object source, ElapsedEventArgs e)
  52. {
  53. try
  54. {
  55. if (deleteTimer.Interval == 1)
  56. {
  57. deleteTimer.Interval = 1000 * 60 * 60 * 24;
  58. }
  59. string path = string.Format(@"{0}", "Logs");
  60. FileInfo[] fileInfos;
  61. DirectoryInfo curFolderInfo = new DirectoryInfo(path);
  62. fileInfos = curFolderInfo.GetFiles();
  63. foreach (FileInfo info in fileInfos)
  64. {
  65. if (info.Name.Contains("log") && (info.Extension == ".txt" || info.Extension == ".log"))
  66. {
  67. DateTime lastWriteTime = DateTime.Parse(info.LastWriteTime.ToShortDateString());
  68. DateTime intervalTime = DateTime.Now.AddDays(-LogsDays);
  69. if (lastWriteTime < intervalTime)
  70. {
  71. File.Delete(info.FullName);
  72. }
  73. }
  74. }
  75. }
  76. catch
  77. {
  78. }
  79. }
  80. public void Terminate()
  81. {
  82. try
  83. {
  84. if (deleteTimer != null)
  85. {
  86. deleteTimer.Enabled = false;
  87. }
  88. }
  89. catch (Exception ex)
  90. {
  91. System.Diagnostics.Trace.WriteLine(ex.Message);
  92. }
  93. }
  94. }
  95. }