Global.asax Application_Error to implement error logging/Error Logging code _ Practical Tips

Source: Internet
Author: User
Tags datetime servervariables
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");
}

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.