本章节将介绍如何以多线程方式下系统日志,并确保每条日志写入不发生冲突,全部写入日志文件。基本原理,将日志写入日志文件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. | } |