Categories
Asp, Asp.net

How to Create Log File in C# Asp.Net

how to create log file in c# asp.net

Hi friends, in this post we will discuss how to create log file in c# asp.netor you can say how to create error log text file in c#, How to create log file to record errors and exceptions in asp.net. Creating a error log file to log all errors and exceptions occurs on our website in a text file is a good idea. It tells developers on which page we have errors so we find it easily and resolve this.

To add log file on a already built website or a new website you just have to follow a few simple steps:

1. Open your website or create a new website.

2. Now Right Click on Application name in Solution Explorer and Go to Add > Add New Item.

How to Create Log File in C#

3. New pop up window will open, Now Choose Global Application Class and click on Add. If you have already a Global Application Class in your website then skip to next step.

How to create log file to record errors and exceptions in asp.net

4. Open Global Application Class and following code on Application_Error Event.

void Application_Error(object sender, EventArgs e) 
    {
        Exception ex = new Exception();
        ex = Server.GetLastError().GetBaseException();

        System.IO.FileStream fs = new System.IO.FileStream(Server.MapPath("~/Errors_Folder/ErrorLOG.txt"), System.IO.FileMode.OpenOrCreate, System.IO.FileAccess.ReadWrite);
        System.IO.StreamWriter s = new System.IO.StreamWriter(fs);
        s.BaseStream.Seek(0, System.IO.SeekOrigin.End);
        s.WriteLine("ERROR DATE: " + System.DateTime.Now.ToString(System.Globalization.CultureInfo.InvariantCulture) + " \nERROR MESSAGE: " + ex.Message + "\nSOURCE: " + ex.Source + "\nFORM NAME: " + System.Web.HttpContext.Current.Request.Url.ToString() + "\nQUERYSTRING: " + Request.QueryString.ToString() + "\nTARGETSITE: " + ex.TargetSite.ToString() + "\nSTACKTRACE: " + ex.StackTrace + System.Diagnostics.EventLogEntryType.Error);
        s.WriteLine("-------------------------------------------------------------------------------------------------------------");
        s.Close();

    }

5. For this to work you need read/write permission on folder, in which our Log File reside.

And we are done, so whenever any error occurs on our website it will automatically logged in our log file.