Log.cs 2.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586
  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 BEMSDataGateway
  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. if (di.Exists != true) //로그 폴더 없을때, 로그 폴더 생성
  25. {
  26. Directory.CreateDirectory(DirPath);
  27. }
  28. if (fi.Exists != true) //로그 파일 없을때, 로그 파일 생성
  29. {
  30. using (StreamWriter sw = new StreamWriter(FilePath))
  31. {
  32. temp = string.Format("[{0}] : {1}", GetDateTime(), str);
  33. sw.WriteLine(temp);
  34. sw.Close();
  35. sw.Dispose();
  36. }
  37. }
  38. else
  39. {
  40. using (StreamWriter sw = File.AppendText(FilePath)) // 로그 파일 있으면, AppendText
  41. {
  42. temp = string.Format("[{0}] : {1}", GetDateTime(), str);
  43. sw.WriteLine(temp);
  44. sw.Close();
  45. sw.Dispose();
  46. }
  47. }
  48. DeleteServiceLogByDay(10); //현재일로부터 10일 이전 로그 파일 삭제
  49. }
  50. internal void DeleteServiceLogByDay(int keepDay)
  51. {
  52. try
  53. {
  54. string DirPath = Application.StartupPath + @"\Logs";
  55. DirectoryInfo di = new DirectoryInfo(DirPath);
  56. foreach (FileInfo file in di.GetFiles())
  57. {
  58. if (file.Extension == ".log")
  59. {
  60. if (file.CreationTime < DateTime.Now.AddDays(-(keepDay)))
  61. {
  62. file.Delete();
  63. }
  64. }
  65. }
  66. di = null;
  67. }
  68. catch (Exception ex)
  69. {
  70. if (Form1.Enable_EnglishMode)//영어
  71. {
  72. Log("[Log.cs] Errors in log file deletion : " + ex);
  73. }
  74. else//한글
  75. {
  76. Log("[Log.cs] 로그 파일 삭제 에러 발생 : " + ex);
  77. }
  78. }
  79. }
  80. }
  81. }