Using Global.asax's Application_Error to implement error logging
Error log
Copy Code code as follows:
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 Browser:" + Request.Browser.Browser.ToString ());
Str. Append ("\r\n\t browser version:" + Request.Browser.MajorVersion.ToString ());
Str. Append ("\r\n\t 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 Source:" + ex.) Source);
Str. Append ("\r\n\t Exception method:" + ex. TargetSite);
Str. Append ("\r\n\t Stack info:" + 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 file Write error
System.IO.File.AppendAllText (Uploadpath + DateTime.Now.ToString ("yyyy"). Mm.dd ") +". Log ", Str. ToString (), System.Text.Encoding.UTF8);
Finish handling the exception in time
Server.ClearError ();
Jump to error page
Response.Redirect ("~/error.html");
}