IT業界のすみっこ暮らし

ふと気がついたときの記録

ASP.NET MVC:全ての例外をログに吐き出す

paulthecyclist.com

App_Start/FilterConfig.cs

using log4net;

public class FilterConfig
{
    public static void RegisterGlobalFilters(GlobalFilterCollection filters, ILog logger)
    {
        filters.Add(new HandleErrorAttribute());
        filters.Add(new ExceptionLoggingFilter(logger));
    }
}

ExceptionLoggingFilter.cs

public class ExceptionLoggingFilter : IExceptionFilter
{
    private readonly ILog _logger;

    public ExceptionLoggingFilter(ILog logger)
    {
        _logger = logger;
    }

    public virtual void OnException(ExceptionContext filterContext)
    {
        _logger.Error(filterContext.Exception);
    }

    public interface IExceptionFilter
    {
        void OnException(ExceptionContext filterContext);
    }
}

Global.asax.cs

protected void Application_Start()
{
    XmlConfigurator.Configure();
    ILog logger = LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);

    AreaRegistration.RegisterAllAreas();
    FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters, logger);

    // other registration
}

追記

エラー発生後の遷移先設定(Global.asax.cs)

protected void Application_Error(object sender, EventArgs e)
{
    Exception ex = Server.GetLastError();
    
    if (ex is HttpException)
    {
        // 404エラーの場合
    }
    else if (ex is InvalidOperationException)
    {
        // 無効な呼び出しの場合
    }
}