When we put the site to the online, in order to understand the operation of the site in real time, such as whether there are error pages, the speed of the site, whether there is an attack. Then it is necessary for us to add errors and exceptions to the log file, so that you can always check the online operation of the site, and another advantage is that when the site has run error page, according to the error log we can quickly to locate the error line to troubleshoot the cause, solve the problem, This is a very necessary feature for a Web site that runs on-line and cannot be debugged.
Specific implementation methods:
Add the Application_Error method to the global file Global.asax.cs. The program automatically executes the method as soon as the program has an error, logging to the error log.
void Application_Error (object sender, EventArgs e) {//code to run in case of unhandled error Exception ex = Server. GetLastError (). GetBaseException (); String errortime ="Exception time:" + DateTime. Now. ToString (); String erroraddress ="Exception Address:" + Request. Url. ToString (); String errorinfo ="Exception info:" + ex. Message; String Errorsource ="Source of Error:" + EX. Source; String ErrorType ="Run Type:" + ex. GetType (); String errorfunction ="Exception function:" + EX. TargetSite; String errortrace ="Stack info:" + ex. StackTrace; Server. ClearError (); System. Io. StreamWriter writer = null; try {Lock (this) {//write log string path = string. Empty; Path = Server. MapPath ("~/errorlogs/"); Does not exist then create error log folder if (! Directory. Exists (Path)) {Directory. CreateDirectory (PATH); } Path +=string. Format (@"\{0}.txt", DateTime. Now. ToString ("Yyyy-mm-dd")); Writer =! File. Exists (path)? File. CreateText (path): File. AppendText (PATH); Determine if the file exists, create if it does not exist, add writer if it exists. WriteLine ("User ip:" + Request. userhostaddress); Writer. WriteLine (Errortime); Writer. WriteLine (erroraddress); Writer. WriteLine (errorinfo); writer. WriteLine (Errorsource); writer. WriteLine (ErrorType); writer. WriteLine (Errorfunction); writer. WriteLine (Errortrace); writer. WriteLine ("********************************************************************************************") ; }} finally {if (writer! = null) {writer. Close ();}} Server. Transfer ("~/500webpage.aspx");//jump to page showing friendly error}
C # Error Exception Log logging to file