2019년 7월 2일 화요일

c# simple thread-safe Log Writer

싱글턴 패턴으로된 로그파일을 생성해주는 클래스이다.
로그파일은 날짜별로 생성되고 각 로그 시간을 함께 찍어준다.
프로그램 시작시 StartDeleteLog / 종료시 StopDeleteLog 한다.
로그파일은 디폴트로 30일이 넘으면 삭제된다.


1:  using System;  
2:  using System.Collections.Generic;  
3:  using System.IO;  
4:  using System.Linq;  
5:  using System.Text;  
6:  using System.Threading;  
7:  using System.Threading.Tasks;  
8:    
9:  namespace MyLog  
10:  {  
11:    public enum LogType  
12:    {  
13:      Info,  
14:      Exception,  
15:      Error  
16:    }  
17:    
18:    public class LogWriter  
19:    {  
20:      public delegate void LogWriteHandlerFunc(LogType logType, DateTime logTime, string logMessage);  
21:      public LogWriteHandlerFunc LogWriteHandler;  
22:    
23:      private static LogWriter instance = new LogWriter();  
24:      public static LogWriter Instance { get { return instance; } }  
25:    
26:      private object objLogLock = new object();  
27:    
28:      private const string LOG_PATH = @"C:\Log\";  
29:      private const string LOG_FILENAME = @"log";  
30:    
31:      private Thread threadDeleteLog;  
32:      private bool bThreadDeleteLogRun = false;  
33:      private int logDeleteDays = 30;  
34:    
35:      public void StartDeleteLog(int days)  
36:      {  
37:        if (!bThreadDeleteLogRun)  
38:        {  
39:          logDeleteDays = days;  
40:          bThreadDeleteLogRun = true;  
41:          threadDeleteLog = new Thread(new ThreadStart(ThreadDeleteLog));  
42:          threadDeleteLog.IsBackground = true;  
43:          threadDeleteLog.Start();  
44:        }  
45:      }  
46:    
47:      public void StopDeleteLog()  
48:      {  
49:        if (threadDeleteLog != null)  
50:        {  
51:          bThreadDeleteLogRun = false;  
52:          threadDeleteLog.Join();  
53:        }  
54:      }  
55:    
56:      private void ThreadDeleteLog()  
57:      {  
58:        CheckLogPath(LOG_PATH);  
59:    
60:        DateTime lastTime = DateTime.MinValue;  
61:    
62:        while (bThreadDeleteLogRun)  
63:        {  
64:          DateTime now = DateTime.Now;  
65:          double diff = (now - lastTime).TotalHours;  
66:          if (diff < 0) diff = 0;  
67:    
68:          if (diff > 24)  
69:          {  
70:            try  
71:            {  
72:              string[] filepaths = Directory.GetFiles(LOG_PATH, "*.txt");  
73:              DeleteLogFiles(now, filepaths);  
74:            }  
75:            catch (Exception ex)  
76:            {  
77:              WriteLog(LogType.Exception, ex.ToString());  
78:            }  
79:    
80:            lastTime = now;  
81:          }  
82:    
83:          Thread.Sleep(100);  
84:        }  
85:      }  
86:    
87:      private void DeleteLogFiles(DateTime now, string[] filepaths)  
88:      {  
89:        foreach (string filepath in filepaths)  
90:        {  
91:          try  
92:          {  
93:            DateTime date = File.GetCreationTime(filepath);  
94:            if ((now - date).TotalDays > logDeleteDays)  
95:            {  
96:              File.Delete(filepath);  
97:            }  
98:          }  
99:          catch (Exception ex)  
100:          {  
101:            WriteLog(LogType.Exception, ex.ToString());  
102:          }  
103:        }  
104:      }  
105:    
106:      public void WriteLog(LogType logType, string log)  
107:      {  
108:        try  
109:        {  
110:          lock (objLogLock)  
111:          {  
112:            Console.WriteLine(log);  
113:    
114:            string filepath = LOG_PATH;  
115:    
116:            CheckLogPath(filepath);  
117:    
118:            DateTime dateTime = DateTime.Now;  
119:            string strDate = dateTime.ToString("yyyyMMdd");  
120:            string strDateTime = dateTime.ToString("yyyy-MM-dd HH:mm:ss.fff");  
121:    
122:            filepath = string.Format("{0}{1}_{2}.txt", filepath, LOG_FILENAME, strDate);  
123:            string logMessage = string.Format("{0} [{1}] {2}", strDateTime, logType, log);  
124:    
125:            using (StreamWriter sw = File.AppendText(filepath))  
126:            {  
127:              sw.WriteLine(logMessage);  
128:              sw.WriteLine("---------------------------------------------------------------------------------------\r");  
129:              sw.Flush();  
130:            }  
131:    
132:            if (LogWriteHandler != null) LogWriteHandler(logType, dateTime, log);  
133:          }  
134:        }  
135:        catch (Exception ex)  
136:        {  
137:          Console.WriteLine(ex.ToString());  
138:        }  
139:      }  
140:    
141:      private void CheckLogPath(string path)  
142:      {  
143:        try  
144:        {  
145:          if (!Directory.Exists(path))  
146:            Directory.CreateDirectory(path);  
147:        }  
148:        catch (Exception ex)  
149:        {  
150:          Console.WriteLine(ex.ToString());  
151:        }  
152:      }  
153:    }  
154:  }  
155:    


private LogWriter logWriter = LogWriter.Instance;
...
logWriter.StartDeleteLog(30);
...
logWriter.WriteLog(LogType.Info, "로그 시작...");
...
logWriter.StopDeleteLog();



댓글 없음:

댓글 쓰기