Java有log4j记录错误日志,而asp.net可以自己写一个来记录错误日志!
- 先封装一个类
using System; using System.Collections.Generic; using System.Linq; using System.Web;using System.IO; using System.Globalization; /// <summary> /// ErrHandler 错误日志处理类 /// </summary> public class ErrHandler { public ErrHandler() { // // TODO: Add constructor logic here // } public static void WriteError(Exception e) { try { ///错误日志记录地址[每天产生一个日志文件] string path = "~/Error/" + DateTime.Today.ToString("dd-MM-yy") + ".log"; if (!File.Exists(System.Web.HttpContext.Current.Server.MapPath(path))) { ///不存在该日志,则创建 File.Create(System.Web.HttpContext.Current.Server.MapPath(path)).Close(); } ///写日志记录 using (StreamWriter w = File.AppendText(System.Web.HttpContext.Current.Server.MapPath(path))) { w.WriteLine("Error Recode:"); w.WriteLine("\tError Time:{0}", DateTime.Now.ToString(CultureInfo.InvariantCulture)); w.WriteLine("\tError Address:" + System.Web.HttpContext.Current.Request.Url.ToString()); w.WriteLine("\tTargetSite:" + e.TargetSite); w.WriteLine("\tError Message:" + e.Message); w.WriteLine("\tError HelpLink:" + e.HelpLink); w.WriteLine("\tError StackTrace:" + e.StackTrace); w.WriteLine("************************************************************************************"); w.WriteLine("\r\n\r\n"); w.Flush(); w.Close(); } } catch (Exception ex) { WriteError(ex); } } }
2.. 类写好了!哪里调用呢? 新建个Global.asax文件吧!
<%@ Application Language="C#" %> <script runat="server"> void Application_Start(object sender, EventArgs e) { // Code that runs on application startup } void Application_End(object sender, EventArgs e) { // Code that runs on application shutdown } void Application_Error(object sender, EventArgs e) { //获取最后的错误 Exception objErr = Server.GetLastError().GetBaseException(); // 这里开始记录咯 ErrHandler.WriteError(objErr);//清除前一个错误Server.ClearError(); } void Session_Start(object sender, EventArgs e) { // Code that runs when a new session is started } void Session_End(object sender, EventArgs e) { // Code that runs when a session ends. // Note: The Session_End event is raised only when the sessionstate mode // is set to InProc in the Web.config file. If session mode is set to StateServer // or SQLServer, the event is not raised. } </script>
这样只要一发生错误了,都会记录到日志里面! 你只需定期去检查错误日志了
当然你也可以在错误中记录,如:
try { throw new Exception("Error"); } catch (Exception ex) { ErrHandler.WriteError(ex); }
OVER
记录学习点滴...,坚持每天让自己的技能增加1%,默默的坚持下去吧!:-)