我们在做项目的时候,经常会使用到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 }
效果展示:
时间: 2024-10-24 23:30:03