Click here to Skip to main content
15,881,812 members
Articles / Web Development
Article

Custom Error Logging

Rate me:
Please Sign up or sign in to vote.
0.00/5 (No votes)
11 Oct 2013CPOL4 min read 7.7K   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. 

 

This article was originally posted at http://wiki.asp.net/page.aspx/383/custom-error-logging

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
United States United States
The ASP.NET Wiki was started by Scott Hanselman in February of 2008. The idea is that folks spend a lot of time trolling the blogs, googlinglive-searching for answers to common "How To" questions. There's piles of fantastic community-created and MSFT-created content out there, but if it's not found by a search engine and the right combination of keywords, it's often lost.

The ASP.NET Wiki articles moved to CodeProject in October 2013 and will live on, loved, protected and updated by the community.
This is a Collaborative Group

754 members

Comments and Discussions

 
-- There are no messages in this forum --