每当遇到程序错误时,将使用者导航到一个单独的页面,同时错误将被记录到服务器上的一个文本文件,每当错误发生时,我们将以日志的形式每天记录。下面学步园小编来讲解下怎样处理记录ASP.NET错误日志?
怎样处理记录ASP.NET错误日志
首先,我先写一个静态方法用于将错误信息记录到文本文件,这里是将错误信息记录到服务器上的Error文件夹下,代码如下:
usingSystem.Globalization;/// ///用于将错误信息输出到txt文件 ///
///
publicstaticvoidWriteError(stringerrorMessage) { try { stringpath="~/Error/"+DateTime.Today.ToString("yyMMdd")+".txt"; if(!File.Exists(System.Web.HttpContext.Current.Server.MapPath(path))) { File.Create(System.Web.HttpContext.Current.Server.MapPath(path)).Close(); } using(StreamWriterw=File.AppendText(System.Web.HttpContext.Current.Server.MapPath(path))) { w.WriteLine("\r\nLogEntry:"); w.WriteLine("{0}",DateTime.Now.ToString(CultureInfo.InvariantCulture)); w.WriteLine(errorMessage); w.WriteLine("________________________________________________________"); w.Flush(); w.Close(); } } catch(Exceptionex) { WriteError(ex.Message); } } 怎样处理记录ASP.NET错误日志 在网站Global.asax文件的Application_Error中加入如下代码 voidApplication_Error(objectsender,EventArgse) { //在出现未处理的错误时运行的代码 ExceptionobjErr=Server.GetLastError().GetBaseException(); //记录出现错误的IP地址 stringstrIP=Request.UserHostAddress; stringerr="Ip【"+strIP+"】"+Environment.NewLine+"Errorin【"+Request.Url.ToString()+ "】"+Environment.NewLine+"ErrorMessage【"+objErr.Message.ToString()+"】"; //记录错误 FN.WriteError(err); }配置Web.Config文件 建立一个GenericErrorPage.htm文件,用于使用者出现错误时呈现的错误页面。 以上就是关于“怎样处理记录ASP.NET错误日志”的内容,希望对大家有用。更多资讯请关注学步园。学步园,您学习IT技术的优质平台!