没有try-catch的log4net捕获错误

时间:2015-06-05 01:51:14

标签: log4net

通常我们会这样做,将异常捕获到我们的日志文件中:

try
{
     Method1();
     Method2();
}
catch (Exception ex)
{
     log.Error(ex.Message);
}

有没有办法,甚至不使用try-catch来捕获错误?

1 个答案:

答案 0 :(得分:0)

您必须在Global.asax文件中进行更改

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();

    }

}