5205bf782b974a139a0f1a8f83071e372c2f860c.svn-base 2.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798
  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. }
  38. }
  39. else
  40. {
  41. using (StreamWriter sw = File.AppendText(FilePath))
  42. {
  43. temp = string.Format("[{0}] : {1}", GetDateTime(), str);
  44. sw.WriteLine(temp);
  45. sw.Close();
  46. }
  47. }
  48. }
  49. catch
  50. {
  51. }
  52. DeleteServiceLogByDay(7); //현재일로부터 7일 이전 로그 파일 삭제
  53. }
  54. internal void DeleteServiceLogByDay(int keepDay)
  55. {
  56. try
  57. {
  58. //string FilePath = Application.StartupPath + @"\Logs\Log" + DateTime.Today.ToString("yyyyMMdd") + ".log";
  59. string DirPath = Application.StartupPath + @"\Logs";
  60. DirectoryInfo di = new DirectoryInfo(DirPath);
  61. foreach (DirectoryInfo dir in di.GetDirectories())
  62. {
  63. foreach (FileInfo file in dir.GetFiles())
  64. {
  65. if (file.Extension != ".log")
  66. {
  67. continue;
  68. }
  69. if (file.CreationTime < DateTime.Now.AddDays(-(keepDay)))
  70. {
  71. file.Delete();
  72. }
  73. }
  74. }
  75. di = null;
  76. }
  77. catch(Exception ex)
  78. {
  79. Log("파일 삭제 에러 발생 = " + ex);
  80. }
  81. }
  82. }
  83. }