Friday, November 30, 2012

Writing Exception Details into a Log File in ASP.NET


To catch the exceptions thrown by the application most of the time we use the Try Catch block but when we need to write those exception details into a log file for later analysis we need the exceptions to be thrown from a common event where we can catch them and write into the log file instead of writing the code within every catch block.

For the above purpose we can use Application_Error event in Global.asax file. Go through the below code

void Application_Error(object sender, EventArgs args)
    {
        // Code that runs when an unhandled error occurs

        Exception e = Server.GetLastError(); // gets the thrown exception
        StringBuilder sb = new StringBuilder();
        sb.Append(Environment.NewLine);
        sb.Append(Environment.NewLine);
        sb.Append("Error" + Environment.NewLine);
        sb.Append("Date Time:" + DateTime.Now + Environment.NewLine);
        sb.Append("Message:" + e.Message + Environment.NewLine);
        sb.Append("Inner Exception:" + e.InnerException + Environment.NewLine);
        sb.Append("Source:" + e.Source + Environment.NewLine);
        sb.Append("Stack Trace:" + e.StackTrace + Environment.NewLine);
        //string path = Server.MapPath("~/Errors.txt");
        string path = @"E:\ErrorFolder\Errors.txt";
 
       System.IO.StreamWriter file = new System.IO.StreamWriter(path, true);
       file.WriteLine(sb);

       file.Close();
 
       Context.ClearError();

    }

No comments:
Write comments
Recommended Posts × +