1. 程式人生 > >C# 後臺添加Log信息

C# 後臺添加Log信息

code bsp 調用 str conf except rec .config 效果展示

我們在做項目的時候,經常會使用到Log日誌,今天分享一下如何在後臺添加Log信息

創建一個寫Log的方法:

 1 public void WriteLog(string Action)
 2     {
 3         try
 4         {
 5             string strLogPath = System.Configuration.ConfigurationManager.AppSettings["LogPath"].ToString();
 6             string strLogName = System.DateTime.Now.ToString("
yyyy/MM/dd").Replace("/", "-"); 7 string strIP = Request.UserHostAddress + ":" + Request.Url.Port;//訪問者的Ip和端口 8 if (!strLogPath.EndsWith("\\")) 9 strLogPath += "\\"; 10 strLogPath += "Log\\"; 11 //判斷是否有這樣的路徑並創建 12 if (System.IO.Directory.Exists(strLogPath) == false
) 13 { 14 System.IO.Directory.CreateDirectory(strLogPath); 15 } 16 strLogName = strLogPath + strLogName + ".txt"; 17 ////如果文件不存在,會自動創建 18 string strNote = System.DateTime.Now.ToString("yyyy/MM/dd HH:mm:ss"); 19 strNote += "
:" + strIP + ":\n" + Action + "\n\n"; 20 System.IO.StreamWriter file = new System.IO.StreamWriter(strLogName, true); 21 file.WriteLine(strNote); 22 file.Close(); 23 file.Dispose(); 24 } 25 catch //(Exception ex) 26 { 27 28 } 29 }

調用事件:

 1 protected void ibtnQuery_Click(object sender, EventArgs e)
 2     {
 3         try
 4         {           
 5             Query();
 6         }
 7         catch (Exception ex) 
 8         { 
 9             WriteLog(ex.Message); 
10         }
11     }    

效果展示:

技術分享

C# 後臺添加Log信息