1. 程式人生 > >多執行緒方式下寫入系統日誌

多執行緒方式下寫入系統日誌

本章節將介紹如何以多執行緒方式下系統日誌,並確保每條日誌寫入不發生衝突,全部寫入日誌檔案。基本原理,將日誌寫入日誌檔案error.log,寫入前先判斷error.log是否可寫,如果不可寫則等待,直到成功寫入為止。error.log其實就是一個文字檔案,當有大量日誌同時寫入時,日誌的先後順序會受影響,但並不會遺漏日誌。

判斷日誌檔案是否可用:

C# Code
1. public static bool IsFileInUse(string fileName)
2. {
3.     bool inUse = true;
4.     System.IO.FileStream fs = null;
5.     try
6.     {
7.         fs = new System.IO.FileStream(fileName,  System.IO.FileMode.Open,  System.IO.FileAccess.Read,  System.IO.FileShare.None);
8.         inUse = false;
9.     }
10.     catch
11.     {
12.         inUse = true;
13.     }
14.     finally
15.     {
16.         if (fs != null)
17.             fs.Close();
18.     }
19.     return inUse;
20. }

多執行緒方式寫入日誌:

C# Code
1. public static void Log(string str)
2. {
3.     string filePath = @appPath + 'error.log';
4.     string content = DateTime.Now.ToString('yyyyMMddHHmmss:') + str;
5.     if (!System.IO.File.Exists(filePath))
6.     {
7.         System.IO.File.AppendAllText(filePath, content);
8.         return;
9.     }
10.     ParameterizedThreadStart threadStart = new ParameterizedThreadStart(WriteLog);
11.     Thread thread = new Thread(threadStart);
12.     thread.Name = 'WebApp.WriteLog';
13.     thread.Start(str);
14. }

向日志文件寫入日誌,其中WriteLog的引數str必須是object型別。

C# Code
1. public static void WriteLog(object str)
2. {
3.     string filePath = @appPath + 'error.log';
4.     string content = '\r\n' + DateTime.Now.ToString('yyyyMMddHHmmss:') + str.ToString();
5.     System.IO.FileInfo info = new System.IO.FileInfo(filePath);
6.     if (info.Length > 1024 * 1024 * 5)
7.     {
8.         while (IsFileInUse(filePath))
9.             Thread.Sleep(100);
10.         System.IO.File.Move(filePath, @appPath + 'error' + DateTime.Now.ToString('yyyyMMdd') + '.log');
11.         System.IO.File.Delete(filePath);
12.     }
13.     while (IsFileInUse(filePath))
14.         Thread.Sleep(100);
15.     if (!IsFileInUse(filePath))
16.     {
17.         #region write file
18.         System.IO.FileStream fs = null;
19.         try
20.         {
21.             fs = new System.IO.FileStream(filePath,  System.IO.FileMode.Append, System.IO.FileAccess.Write,  System.IO.FileShare.None);
22.             fs.Write(Encoding.UTF8.GetBytes(content), 0, Encoding.UTF8.GetByteCount(content));
23.         }
24.         catch
25.         {
26.             ;
27.         }
28.         finally
29.         {
30.             if (fs != null)
31.                 fs.Close();
32.         }
33.         #endregion
34.     }
35. }