Home > ASP.Net > Log Any Error in Website

Log Any Error in Website

Hi all

I’m going now to give example to show how to log any error can be accoured in website like any Exception in txt file

First in root of my website i should create Folder for example i’ll create Error folder which will contain txt files which will be created if any Error accoured in my website and don’t forget to give that folder premission for Rad/Write

Second thing Create Class called ErrHandler.cs which have the following code :-

using System;
using System.Data;
using System.Configuration;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.IO;
using System.Globalization;
public class ErrHandler
    private static string IsErrorLogEnabled = System.Configuration.ConfigurationManager.AppSettings["EnableErrorBLog"];
    /// Handles error by accepting the error message
    /// Displays the page on which the error occured
    public static void WriteError(string errorMessage)
        if (IsErrorLogEnabled == "True")
                string CurrentDay = System.DateTime.Now.Day.ToString();
                string CurrentMonth = System.DateTime.Now.Month.ToString();
                string CurrentYear = System.DateTime.Now.Year.ToString();
                string LogFileName = CurrentDay + "-" + CurrentMonth + "-" + CurrentYear + ".txt";
                string path = "~/Error/" + LogFileName;
                if (!File.Exists(System.Web.HttpContext.Current.Server.MapPath(path)))
                using (StreamWriter w = File.AppendText(System.Web.HttpContext.Current.Server.MapPath(path)))
                    w.WriteLine("\r\nLog Entry : ");
                    w.WriteLine("{0}", DateTime.Now.ToString("dd/MM/yyyy hh:mm:ss"));
                    string err = "Error in: " + System.Web.HttpContext.Current.Request.Url.ToString() +
                                  ". Error Message:" + errorMessage;
            catch (Exception ex)

and In Web.Config i’ll add line to Enable and Disable Error Logging

  <add key="EnableErrorBLog" value="True"/>

and to use this call try make your Code between Try and Catch block

      //-- any code here
catch (Exception ex)

Hope this helps

Good Luck.

Categories: ASP.Net
  1. No comments yet.
  1. No trackbacks yet.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s

%d bloggers like this: