1. 程式人生 > >自定義Log 寫到文件中

自定義Log 寫到文件中

public stream ndt generic file alt IT ram --

  1. using System;
  2. using System.Collections.Generic;
  3. using System.Web;
  4. using System.IO;
  5. using System.Text;
  6. /// <summary>
  7. /// Summary description for NetLog
  8. /// </summary>
  9. public class NetLog
  10. {
  11. /// <summary>
  12. /// 寫入日誌到文本文件
  13. /// </summary>
  14. /// <param name="action">動作</param>
  15. /// <param name="strMessage">日誌內容</param>
  16. /// <param name="time">時間</param>
  17. public static void WriteTextLog(string action, string strMessage, DateTime time)
  18. {
  19. string path = AppDomain.CurrentDomain.BaseDirectory + @"System\Log\";
  20. if (!Directory.Exists(path))
  21. Directory.CreateDirectory(path);
  22. string fileFullPath = path + time.ToString("yyyy-MM-dd") + ".System.txt";
  23. StringBuilder str = new StringBuilder();
  24. str.Append("Time: " + time.ToString() + "\r\n");
  25. str.Append("Action: " + action + "\r\n");
  26. str.Append("Message: " + strMessage + "\r\n");
  27. str.Append("-----------------------------------------------------------\r\n\r\n");
  28. StreamWriter sw;
  29. if (!File.Exists(fileFullPath))
  30. {
  31. sw = File.CreateText(fileFullPath);
  32. }
  33. else
  34. {
  35. sw = File.AppendText(fileFullPath);
  36. }
  37. sw.WriteLine(str.ToString());
  38. sw.Close();
  39. }
  40. }

自定義Log 寫到文件中