Global. asax's Application_Error implements the code for error logging and error logs

  • 2020-06-19 10:04:51
  • OfStack

Use Application_Error of ES0en. asax to achieve error logging

The error log
 
void Application_Error(object sender, EventArgs e) 
{ 
//  Code that runs when an unhandled error occurs  
Exception ex = Server.GetLastError().GetBaseException(); 
StringBuilder str = new StringBuilder(); 
str.Append("\r\n" + DateTime.Now.ToString("yyyy.MM.dd HH:mm:ss")); 
str.Append("\r\n. Customer information: "); 


string ip = ""; 
if (Request.ServerVariables.Get("HTTP_X_FORWARDED_FOR") != null) 
{ 
ip = Request.ServerVariables.Get("HTTP_X_FORWARDED_FOR").ToString().Trim(); 
} 
else 
{ 
ip = Request.ServerVariables.Get("Remote_Addr").ToString().Trim(); 
} 
str.Append("\r\n\tIp:" + ip); 
str.Append("\r\n\t The browser :" + Request.Browser.Browser.ToString()); 
str.Append("\r\n\t Browser version :" + Request.Browser.MajorVersion.ToString()); 
str.Append("\r\n\t The operating system :" + Request.Browser.Platform.ToString()); 
str.Append("\r\n. Error message: "); 
str.Append("\r\n\t Page: " + Request.Url.ToString()); 
str.Append("\r\n\t Error message: " + ex.Message); 
str.Append("\r\n\t Error sources: " + ex.Source); 
str.Append("\r\n\t Exception method: " + ex.TargetSite); 
str.Append("\r\n\t Stack information: " + ex.StackTrace); 
str.Append("\r\n--------------------------------------------------------------------------------------------------"); 
// Create a path  
string upLoadPath = Server.MapPath("~/log/"); 
if (!System.IO.Directory.Exists(upLoadPath)) 
{ 
System.IO.Directory.CreateDirectory(upLoadPath); 
} 
// Create a file   Write error  
System.IO.File.AppendAllText(upLoadPath + DateTime.Now.ToString("yyyy.MM.dd") + ".log", str.ToString(), System.Text.Encoding.UTF8); 
// Deal with and clean up the exception in time  
Server.ClearError(); 
// Jump to the error page  
Response.Redirect("~/error.html"); 
} 

Related articles: