Global ASP.NET Application Error Logging With Log4Net

In your UI project’s Global.asax.cs:

using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.SessionState;
using log4net;



namespace YourNameSpace
{
    public class Global : System.Web.HttpApplication
    {

        /// <summary>
        /// Gets the log.
        /// </summary>
        /// <value>The log.</value>
        public ILog log
        {
            get { return LogManager.GetLogger("YourAppNameLogger"); }
        }


        protected void Application_Start(object sender, EventArgs e)
        {
            log4net.Config.XmlConfigurator.Configure();

        }

        protected void Application_End(object sender, EventArgs e)
        {

        }
        
        /// <summary>
        /// Handles the Error event of the Application control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param>
        protected void Application_Error(object sender, EventArgs e)
        {
            log.Fatal("Site Application_Error", Server.GetLastError());
            Response.Redirect("/SiteException.aspx", false);
            System.Web.HttpContext.Current.ApplicationInstance.CompleteRequest();
            Server.ClearError();
        }


    }
}

Create SiteException.aspx :

<div id="error">
        <img alt="Error Symbol" src="Images/error.png" />
        <p>
            We're sorry but an error was encountered while processing your request.
        </p>
        <p>
            Please try submitting your request again.</p>
        <p>
        </p>
        <p>
            If the problem persists please contact the administrators at 000.000.0000</p>
    </div>

And you can test this in a page by doing the following in a dummy test page:

 public partial class Default : System.Web.UI.Page
    {
        void Page_Load(object sender, System.EventArgs e)
        {
           // test global error handling
            throw (new ArgumentNullException());

        }
    }

It should redirect you to the SiteException.aspx page as an error was thrown.

Advertisements

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 )

Twitter picture

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

Facebook photo

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

Google+ photo

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

Connecting to %s