Log.cs 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172
  1. using System;
  2. using System.Linq;
  3. using System.Text;
  4. using System.Reflection;
  5. using System.IO;
  6. using System.Threading.Tasks;
  7. namespace ZLPlugin_LisPacs_MR.Domain.Units
  8. {
  9. /// <summary>
  10. /// 自定义日志类
  11. /// </summary>
  12. class Log
  13. {
  14. /// <summary>
  15. /// 日志路径
  16. /// </summary>
  17. static string Path { get; set; }
  18. /// <summary>
  19. /// 记录日志
  20. /// </summary>
  21. /// <param name="info"></param>
  22. /// <param name="isNewline">是否换行(目前体现排版的空行)</param>
  23. public static void Info(string info, bool isNewline = false)
  24. {
  25. if (string.IsNullOrEmpty(Path) || Path?.Length == 0)
  26. GetPath();
  27. var file = Path + "\\" + DateTime.Now.ToString("yyyy-MM-dd") + ".Log";
  28. using (var sw = new StreamWriter(file, true, Encoding.UTF8))
  29. {
  30. sw.WriteLine(DateTime.Now.ToString() + "=====>" + info);
  31. if (isNewline)
  32. sw.WriteLine();
  33. sw.Flush();
  34. }
  35. }
  36. /// <summary>
  37. /// 获取日志路径(以部件名称为文件夹名称)
  38. /// </summary>
  39. /// <returns></returns>
  40. public static string GetPath()
  41. {
  42. var file = "C:\\zlPlugIn_调试信息";
  43. if (!Directory.Exists(file))
  44. Directory.CreateDirectory(file);
  45. Path = file + "\\" + Assembly.GetExecutingAssembly().GetName().Name;
  46. if (!Directory.Exists(Path))
  47. Directory.CreateDirectory(Path);
  48. return Path;
  49. }
  50. /// <summary>
  51. /// 异步删除日志任务
  52. /// </summary>
  53. /// <returns></returns>
  54. public static Task ClearLogAsyn(int Day = 20)
  55. {
  56. return new Task(() =>
  57. {
  58. var files = new DirectoryInfo(GetPath()).GetFiles("*.Log");
  59. files.ToList().ForEach(n =>
  60. {
  61. if ((DateTime.Now - n.LastAccessTime).TotalDays > Day)
  62. n.Delete();
  63. });
  64. });
  65. }
  66. }
  67. }