Create an error log file - ASPMANTRA | Asp.Net,MVC,AngularJs,Jquery,Javascript,Sql Server AND WCF snippets and tutorial Create an error log file

Introduction: In this article I will explain how to create an error log file in

Error log file is useful to capture runtime errors and exceptions of website to a file. In this example I will create a text error log file. Follow the below given steps to implement:

Step 1: Add a Global.asax file to Project/website if not exist.

Step 2: Now add the namespace to Global.asax file.
<%@ Import Namespace="System.IO" %>

Step 3: After that write the below given code in Application_Error event of Global file: 
void Application_Error(object sender, EventArgs e)
        // Code that runs when an unhandled error occurs
        Exception ex = new Exception();
        ex = Server.GetLastError().GetBaseException();

        FileStream fs = new FileStream(Server.MapPath("~/ErrorLOG.txt"), FileMode.OpenOrCreate, FileAccess.ReadWrite);
        StreamWriter sw = new StreamWriter(fs);
        sw.BaseStream.Seek(0, System.IO.SeekOrigin.End);
        sw.WriteLine("ERROR DATE: " + System.DateTime.Now.ToString(System.Globalization.CultureInfo.InvariantCulture));
        sw.Write("ERROR MESSAGE: " + ex.Message);
        sw.Write("SOURCE: " + ex.Source);
         sw.Write("FORM NAME: " + System.Web.HttpContext.Current.Request.Url.ToString());
         sw.Write("QUERYSTRING: " + Request.QueryString.ToString());
         sw.Write("TARGETSITE: " + ex.TargetSite.ToString());
         sw.Write("STACKTRACE: " + ex.StackTrace + System.Diagnostics.EventLogEntryType.Error);

When any error or exception occurs in website/project, error writes to ErrorLOG text file.

What do you think about this article?

If you found this article useful, please share and follow on Facebook, Twitter, Google Plus and other social media websites. To get free updates subscribe to newsletter. Please put your thoughts and feedback in comments section.