自定义Log 写到文件中

  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.Web;  
  4. using System.IO;  
  5. using System.Text;  
  6.   
  7. /// <summary>  
  8. /// Summary description for NetLog  
  9. /// </summary>  
  10. public class NetLog  
  11. {  
  12.     /// <summary>  
  13.     /// 写入日志到文本文件  
  14.     /// </summary>  
  15.     /// <param name="action">动作</param>  
  16.     /// <param name="strMessage">日志内容</param>  
  17.     /// <param name="time">时间</param>  
  18.     public static void WriteTextLog(string action, string strMessage, DateTime time)  
  19.     {  
  20.         string path = AppDomain.CurrentDomain.BaseDirectory + @"SystemLog";  
  21.         if (!Directory.Exists(path))  
  22.             Directory.CreateDirectory(path);  
  23.   
  24.         string fileFullPath = path + time.ToString("yyyy-MM-dd") + ".System.txt";  
  25.         StringBuilder str = new StringBuilder();  
  26.         str.Append("Time:    " + time.ToString() + " ");  
  27.         str.Append("Action:  " + action + " ");  
  28.         str.Append("Message: " + strMessage + " ");  
  29.         str.Append("----------------------------------------------------------- ");  
  30.         StreamWriter sw;  
  31.         if (!File.Exists(fileFullPath))  
  32.         {  
  33.             sw = File.CreateText(fileFullPath);  
  34.         }  
  35.         else  
  36.         {  
  37.             sw = File.AppendText(fileFullPath);  
  38.         }  
  39.         sw.WriteLine(str.ToString());  
  40.         sw.Close();  
  41.     }  
  42. }  
原文地址:https://www.cnblogs.com/TddCoding/p/8831581.html