Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

log4net log all unhandled application errors

Can you point me to some tutorial or samples on how I can log all un-handled exceptions that are occurring on my mvc web app using log4net. Thank you

like image 279
kaivalya Avatar asked Sep 02 '09 14:09

kaivalya


4 Answers

I paste below the code I use on my global.asax that seems to satisfy me for now.. I am getting all unhandled exceptions on my log4net generated log files..

    public class MvcApplication : System.Web.HttpApplication
    {

        private static readonly ILog log = LogManager.GetLogger(typeof(MvcApplication));

        void Application_Error(Object sender, EventArgs e)
        {
            Exception ex = Server.GetLastError().GetBaseException();

            log.Error("App_Error", ex);
        }


        public static void RegisterRoutes(RouteCollection routes)
        {
            routes.IgnoreRoute("{resource}.axd/{*pathInfo}");

            routes.MapRoute(
                "Default",
                "{controller}/{action}/{id}",
                new { controller = "Home", action = "Index", id = "" }
            );

        }

        protected void Application_Start()
        {
            RegisterRoutes(RouteTable.Routes);
            log4net.Config.XmlConfigurator.Configure();

        }

    }
like image 122
kaivalya Avatar answered Nov 20 '22 20:11

kaivalya


For ASP.NET applications you like to use the System.Web.HttpApplication.Error event which is placed in Global.asax file.

protected void Application_Error(Object sender, EventArgs e)
{
    Exception ex = Server.GetLastError();

    // Stop error from displaying on the client browser
    Context.ClearError();

    logger.Fatal(ex.ToString);

}

watch Managing unhandled exceptions

like image 44
eljhonb Avatar answered Nov 20 '22 21:11

eljhonb


You might be interested to check out what Aspect Oriented Programming (AOP) is.

We accomplished this with Post sharp (only - we didn't use log4net but custom tracer).

Just check out first if log4net haven't something for this 'out-of-the-box'. I'm not sure about that.

like image 2
Arnis Lapsa Avatar answered Nov 20 '22 19:11

Arnis Lapsa


There is no built-in support for this in log4net. You should implement the Application_Error event in Global.asax and call your log4net logger there. The event will be triggered for all unhandled events in your app.

like image 2
Peter Lillevold Avatar answered Nov 20 '22 19:11

Peter Lillevold