Log.cs 2.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Text;
  5. using System.Diagnostics;
  6. using System.IO;
  7. using System.Windows.Forms;
  8. namespace DataGateWayProject
  9. {
  10. class LogFileCreate
  11. {
  12. public string GetDateTime()
  13. {
  14. DateTime NowDate = DateTime.Now;
  15. return NowDate.ToString("yyyy-MM-dd HH:mm:ss") + ":" + NowDate.Millisecond.ToString("000");
  16. }
  17. public void Log(string str) //로그 기록 함수
  18. {
  19. string FilePath = Application.StartupPath + @"\Logs\Log" + DateTime.Today.ToString("yyyyMMdd") + ".log";
  20. string DirPath = Application.StartupPath + @"\Logs";
  21. string temp;
  22. DirectoryInfo di = new DirectoryInfo(DirPath);
  23. FileInfo fi = new FileInfo(FilePath);
  24. try
  25. {
  26. if (di.Exists != true)
  27. {
  28. Directory.CreateDirectory(DirPath);
  29. }
  30. if (fi.Exists != true)
  31. {
  32. using (StreamWriter sw = new StreamWriter(FilePath))
  33. {
  34. temp = string.Format("[{0}] : {1}", GetDateTime(), str);
  35. sw.WriteLine(temp);
  36. sw.Close();
  37. sw.Dispose();
  38. }
  39. }
  40. else
  41. {
  42. using (StreamWriter sw = File.AppendText(FilePath))
  43. {
  44. temp = string.Format("[{0}] : {1}", GetDateTime(), str);
  45. sw.WriteLine(temp);
  46. sw.Close();
  47. sw.Dispose();
  48. }
  49. }
  50. }
  51. catch
  52. {
  53. }
  54. DeleteServiceLogByDay(10); //현재일로부터 7일 이전 로그 파일 삭제
  55. }
  56. internal void DeleteServiceLogByDay(int keepDay)
  57. {
  58. try
  59. {
  60. string DirPath = Application.StartupPath + @"\Logs";
  61. DirectoryInfo di = new DirectoryInfo(DirPath);
  62. foreach (FileInfo file in di.GetFiles())
  63. {
  64. if (file.Extension == ".log")
  65. {
  66. if (file.CreationTime < DateTime.Now.AddDays(-(keepDay)))
  67. {
  68. file.Delete();
  69. }
  70. }
  71. }
  72. di = null;
  73. }
  74. catch (Exception ex)
  75. {
  76. Log("[Log.cs]파일 삭제 에러 발생 = " + ex);
  77. }
  78. }
  79. }
  80. }