Friday, May 29, 2015

Asp.net Create an error log file

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

Description:
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("\r\n");
        sw.Write("ERROR MESSAGE: " + ex.Message);
        sw.Write("\r\n");
        sw.Write("SOURCE: " + ex.Source);
        sw.Write("\r\n");
         sw.Write("FORM NAME: " + System.Web.HttpContext.Current.Request.Url.ToString());
         sw.Write("\r\n");
         sw.Write("QUERYSTRING: " + Request.QueryString.ToString());
         sw.Write("\r\n");
         sw.Write("TARGETSITE: " + ex.TargetSite.ToString());
         sw.Write("\r\n");
         sw.Write("STACKTRACE: " + ex.StackTrace + System.Diagnostics.EventLogEntryType.Error);
         sw.Write("\r\n");
        sw.WriteLine("-----------------------------------------------------------------------------------------");
        sw.Close();
      }

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


No comments:

Post a Comment