LogManager.cs 2.7 KB

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