Thursday 15 November 2012

Create Text Log File to Handle Exception


Create Text Log File to Handle Exception


I wanted to create a text file whenever an exception occurs in my page.. This is how you too can do that:

Include the namespaces:


using System.IO;

using System.Globalization;


I am doing this for handling an exception on linkbutton click:


    protected void LinkButton1_Click(object sender, EventArgs e)

    {

        try

        {

           // Your Codes

        }

        catch(Exception ex)

        {

            WriteToEventLog(ex);

        }

    }


Here is the method to achieve this:



    public static void WriteToEventLog(Exception exception)

    {

        string sPath = "~/error/" + DateTime.Today.ToString("dd-MM-yy") + ".txt";

        if (!File.Exists(System.Web.HttpContext.Current.Server.MapPath(sPath)))

        {

        File.Create(System.Web.HttpContext.Current.Server.MapPath(sPath)).Close();

        }

        StreamWriter objStreamWriter = File.AppendText(System.Web.HttpContext.Current.Server.MapPath(sPath));

        {

        objStreamWriter.WriteLine("\r\nLog Entry : ");

        objStreamWriter.WriteLine("{0}", DateTime.Now.ToString(CultureInfo.InvariantCulture));

        string sError = "Error in: " + System.Web.HttpContext.Current.Request.Url.ToString() +". Error Message:\n" + exception.Message;

        objStreamWriter.WriteLine(sError);

        objStreamWriter.WriteLine("__________________________");

        objStreamWriter.Flush();

        objStreamWriter.Close();

        }

    }

No comments:

Post a Comment

Thank You for Your Comments. We will get back to you soon.

back to top