效果:
描述:將系統中的錯誤信息,try catch到日志裡面。
代碼:
【後端代碼】
1 using System; 2 using System.Collections.Generic; 3 using System.Configuration; 4 using System.IO; 5 using System.Linq; 6 using System.Web; 7 8 namespace GetLog 9 { 10 public class WriteLog 11 { 12 private static StreamWriter streamWriter; //寫文件 13 14 public static void WriteError(string message) 15 { 16 try 17 { 18 //DateTime dt = new DateTime(); 19 string directPath = ConfigurationManager.AppSettings["LogFilePath"].ToString().Trim(); //獲得文件夾路徑 20 if (!Directory.Exists(directPath)) //判斷文件夾是否存在,如果不存在則創建 21 { 22 Directory.CreateDirectory(directPath); 23 } 24 directPath += string.Format(@"\{0}.log", DateTime.Now.ToString("yyyy-MM-dd")); 25 if (streamWriter == null) 26 { 27 streamWriter = !File.Exists(directPath) ? File.CreateText(directPath) : File.AppendText(directPath); //判斷文件是否存在如果不存在則創建,如果存在則添加。 28 } 29 streamWriter.WriteLine("***********************************************************************"); 30 streamWriter.WriteLine(DateTime.Now.ToString("HH:mm:ss")); 31 streamWriter.WriteLine("輸出信息:錯誤信息"); 32 if (message != null) 33 { 34 streamWriter.WriteLine("異常信息:\r\n" + message); 35 } 36 } 37 finally 38 { 39 if (streamWriter != null) 40 { 41 streamWriter.Flush(); 42 streamWriter.Dispose(); 43 streamWriter = null; 44 } 45 } 46 } 47 } 48 }
【調用】:
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.UI; using System.Web.UI.WebControls; namespace GetLog { public partial class testLog : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e) { } protected void btn_Click(object sender, EventArgs e) { try { int intStr=Convert.ToInt32(tb.Text); tb2.Text ="轉換成功:" +intStr.ToString(); } catch (Exception ex) { WriteLog.WriteError(ex.ToString()); throw ex; } } } }
Demo下載:
http://files.cnblogs.com/files/xinchun/GetLog.zip