LogManager.cs 2.6 KB

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