Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles
(untagged)

Custom Error Logging

0.00/5 (No votes)
27 Apr 2008 1  
This article presents a way to log and mail the errors from any web page.It logs following details -Control on which the error is raisedPage

This articles was originally at wiki.asp.net but has now been given a new home on CodeProject. Editing rights for this article has been set at Bronze or above, so please go in and edit and update this article to keep it fresh and relevant.

This article presents a way to log and mail the errors from any web page.

It logs following details -

  • Control on which the error is raised
  • Page which controls the error
  • Error Description
  • Trace Messages
  • Server and Client details

Log is created in log folder under root directory.

 
Source code is provided in class file errorHandler.cs



using System;
using System.Data;
using System.Configuration;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;
using System.Net.Mail;
using System.IO;


/// <summary>
/// this class is designed to log errors and send mails regarding
/// runtime errors in myweb portal.
///
/// Developer : yeotumitsu@sify.com
/// Date: 24-04-2008
/// Modified on: 25-04-2008
/// </summary>

public enum MessageType // enum is accessed to provide the operation to be done
{
    EventLog,
    SendMail,
    MailAndEventLog
}


public class errorHandler
{
    public MessageType MsgType
    {
        get
        {
            return this.MT;
        }
        set
        {
            this.MT = value;
        }
    }

    public MessageType MT = new MessageType();
  
    public string EmailReciever = "";
    public string LogName = "";
    public string MailServer = "";
    public string MailSubject = "Error Report " + HttpContext.Current.Request.ServerVariables["SERVER_NAME"];
    

    public errorHandler() // sets default values of the fields
    {
        this.MailServer = ConfigurationSettings.AppSettings["MailServer"];
        this.EmailReciever = ConfigurationSettings.AppSettings["MailReciever"];
        this.LogName = ConfigurationSettings.AppSettings["LogName"];
    }

    /// <summary>
    /// function errorHandler overloaded.
    /// sets the default values if provided by the user.
    /// </summary>
    /// <param name="_mailserver"> SMTP server IP </param>
    /// <param name="_mailreciever"> E mail id of person who is supposed to recieve error mails </param>
    /// <param name="_logname"> name of the error log </param>
  
    public errorHandler(string _mailserver, string _mailreciever, string _logname)
    {
        this.MailServer        = _mailserver;
        this.EmailReciever    = _mailreciever;
        this.LogName        = _logname;
    }

    /// <summary>
    /// raiseError is called to select the operation to be done
    /// </summary>
    /// <param name="_message"> any message </param>
    /// <param name="ex"> exception  </param>
    public void RaiseError(string _message, Exception ex)
    {
       switch (this.MT)
        {
            case MessageType.EventLog:
                SaveToEventLog(_message, ex);
                break;
            case MessageType.SendMail:
                sendErrorMail(_message);
                break;
            case MessageType.MailAndEventLog:
                SaveToEventLog(_message, ex);
                sendErrorMail(_message);
                break;
            default:
                break;
        }
    }

    /// <summary>
    /// Sends mail to the person specified to recieve mails
    /// </summary>
    /// <param name="_message"> message to send </param>
    /// <returns> </returns>
    public int sendErrorMail(string _message)
    {
        MailMessage errorMessage = new MailMessage();
        errorMessage.To.Add(new MailAddress(this.EmailReciever));
        errorMessage.Subject = this.MailSubject;
        errorMessage.IsBodyHtml = true;
        errorMessage.Priority = MailPriority.High;
        errorMessage.Body = _message + " Please check log for more information.";
        SmtpClient clientSmtp = new SmtpClient();
        try
        {
            clientSmtp.Send(errorMessage);
        }
        catch
        {
            return 0;
        }
        return 1;
    }


    /// <summary>
    /// Formats and logs error
    /// </summary>
    /// <param name="_message"> any message </param>
    /// <param name="ex"> exception  </param>
  
    private void SaveToEventLog(string _message, Exception ex)
    {
        try
        {
            string strPhysicalApplicationPath = HttpContext.Current.Request.PhysicalApplicationPath;
            string strFileName = strPhysicalApplicationPath + "Logs\\" + LogName + DateTime.Now.ToString("ddMMMyyyy") + ".txt";
            string strBody = string.Empty;
            FileInfo fInfo = new FileInfo(strFileName);

            strBody = _message + Environment.NewLine + Environment.NewLine;
            strBody +=  "Server Address :: " + HttpContext.Current.Request.ServerVariables["SERVER_NAME"] + Environment.NewLine;
            strBody += "User Address   :: " + HttpContext.Current.Request.ServerVariables["REMOTE_HOST"] + Environment.NewLine;
            strBody += "Script Name    :: " + HttpContext.Current.Request.ServerVariables["SCRIPT_NAME"] + Environment.NewLine;
            strBody += "Query Data     :: " + HttpContext.Current.Request.Url.Query + Environment.NewLine;
            strBody += "Occured At     :: " + DateTime.Now + Environment.NewLine + Environment.NewLine;
            strBody += "################################## -- Start of Error  -- #################################" + Environment.NewLine;
            strBody += ex.StackTrace + Environment.NewLine;
            strBody += "################################### -- End of Error -- ###################################" + Environment.NewLine + Environment.NewLine;
            strBody += HttpContext.Current.Request.ServerVariables["ALL_HTTP"] + Environment.NewLine;

            DirectoryInfo dInfo = new DirectoryInfo(strPhysicalApplicationPath + "Logs\\");
            if (!dInfo.Exists)
            {
                dInfo.Create();
            }

            if (fInfo.Exists)
            {
                FileStream fStream = new FileStream(strFileName, FileMode.Append, FileAccess.Write);
                StreamWriter sWriter = new StreamWriter(fStream);
                sWriter.WriteLine(strBody);
                sWriter.Close();
            }
            else
            {
                FileStream fStream = new FileStream(strFileName, FileMode.Create, FileAccess.Write);
                StreamWriter sWriter = new StreamWriter(fStream);
                sWriter.WriteLine(strBody);
                sWriter.Close();
            }
        }
        catch (Exception e)
        {
            sendErrorMail(e.Message);
        }
    }
}


Web config serrings -  

 <appSettings>
        <add key="MailServer" value="127.0.0.1"/>
        <add key="MailReciever" value="you@yourSite.com"/>
        <add key="LogName" value="EmpostErrLog"/>
    </appSettings>
    <system.net>
        <mailSettings>
            <smtp from="admin@yourSite.com">
                <network host="127.0.0.1"/>
            </smtp>
        </mailSettings>
    </system.net>

 


Calling the method -

 catch(Exception ex)
        {
            string strMsg = "Date : " + DateTime.Now.ToString("dd/MMM/yyyy HH:mm:ss") + "  Error : " + ex.Message + " Control : " + ((Control)sender).ClientID.ToString() + " Page :  " + Page;
            errorHandler objErrorHandler = new errorHandler();
            objErrorHandler.MsgType = MessageType.MailAndEventLog;
            objErrorHandler.RaiseError(strMsg,ex);
        }

 

 


Hope it Helps. 

 

License

This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here