Making log4Net work with Custom Errors in MVC

By | November 17, 2017

The problem when you use Custom Errors declared on your web.config is that the Application_Error on your Global.asax does not fire.  So if you have some log4Net logging methods on the Application_Error section then you are out of luck, it will never log your exception anymore but there are work around and here is how I made mine.


I was using log4Net for quite sometime and since most of the web applications I built was internal I never bothered making custom Error Pages until now. The minute I added this to my web.config

<customErrors mode="OndefaultRedirect="~/Error/">
  <error redirect="~/Error/NotFoundstatusCode="404" />
  <error redirect="~/Error/ServerErrorstatusCode="500" />
</customErrors>

The Application_Error section on my Global.asax stopped firing, to resolve that I started to use ActionFilterAttribute and I created my own handler to catch that error, instantiating it on my Applciation_Start and I am back to business.

So before if it looks like this.

public class MvcApplication : System.Web.HttpApplication
{
       
    private static readonly ILog Log = LogManager.GetLogger(typeof(MvcApplication));
 
    protected void Application_Error(object sender, EventArgs e)
    {
        var exception = this.Server.GetLastError();
        Log.Error("Unhandled exception logged in Application." + Environment.NewLine + 
            "User : " + AuthenticationHelper.GetCurrentAuthenticatedUserName() + Environment.NewLine + 
            "Page : " + HttpContext.Current.Request.Url.AbsoluteUri, exception);
 
    }
 
    protected void Application_Start()
    {
        AreaRegistration.RegisterAllAreas();
        FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
        RouteConfig.RegisterRoutes(RouteTable.Routes);
        BundleConfig.RegisterBundles(BundleTable.Bundles);
        log4net.Config.XmlConfigurator.Configure();
 
        Bootstrapper.Initialise();
    }
}

Now I created a class for my Custom Error Handler

public class ExecuteCustomErrorHandler : ActionFilterAttributeIExceptionFilter
{
    private static readonly ILog Log = LogManager.GetLogger(typeof(MvcApplication));
 
    public void OnException(ExceptionContext filterContext)
    {
        Log.Error("Unhandled exception logged in Application." + Environment.NewLine + 
            "User : " + AuthenticationHelper.GetCurrentAuthenticatedUserName() + Environment.NewLine + 
            "Page : " + HttpContext.Current.Request.Url.AbsoluteUri, filterContext.Exception);
 
    }
}

Register it on Application_Start so it looks like this

protected void Application_Start()
{
    AreaRegistration.RegisterAllAreas();
    FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
    RouteConfig.RegisterRoutes(RouteTable.Routes);
    BundleConfig.RegisterBundles(BundleTable.Bundles);
    log4net.Config.XmlConfigurator.Configure();
    GlobalFilters.Filters.Add(new ExecuteCustomErrorHandler());
 
    Bootstrapper.Initialise();
}

Now its logging my errors again normally.


Leave a Reply