How to get ELMAH to work with ASP.NET MVC [HandleError] attribute?

前端 未结 8 1959
后悔当初
后悔当初 2020-11-22 02:53

I am trying to use ELMAH to log errors in my ASP.NET MVC application, however when I use the [HandleError] attribute on my controllers ELMAH doesn\'t log any errors when the

相关标签:
8条回答
  • 2020-11-22 03:00

    A completely alternative solution is to not use the MVC HandleErrorAttribute, and instead rely on ASP.Net error handling, which Elmah is designed to work with.

    You need to remove the default global HandleErrorAttribute from App_Start\FilterConfig (or Global.asax), and then set up an error page in your Web.config:

    <customErrors mode="RemoteOnly" defaultRedirect="~/error/" />
    

    Note, this can be an MVC routed URL, so the above would redirect to the ErrorController.Index action when an error occurs.

    0 讨论(0)
  • 2020-11-22 03:03

    This is exactly what I needed for my MVC site configuration!

    I added a little modification to the OnException method to handle multiple HandleErrorAttribute instances, as suggested by Atif Aziz:

    bear in mind that you may have to take care that if multiple HandleErrorAttribute instances are in effect then duplicate logging does not occur.

    I simply check context.ExceptionHandled before invoking the base class, just to know if someone else handled the exception before current handler.
    It works for me and I post the code in case someone else needs it and to ask if anyone knows if I overlooked anything.

    Hope it is useful:

    public override void OnException(ExceptionContext context)
    {
        bool exceptionHandledByPreviousHandler = context.ExceptionHandled;
    
        base.OnException(context);
    
        Exception e = context.Exception;
        if (exceptionHandledByPreviousHandler
            || !context.ExceptionHandled  // if unhandled, will be logged anyhow
            || RaiseErrorSignal(e)        // prefer signaling, if possible
            || IsFiltered(context))       // filtered?
            return;
    
        LogException(e);
    }
    
    0 讨论(0)
  • 2020-11-22 03:04

    There is now an ELMAH.MVC package in NuGet that includes an improved solution by Atif and also a controller that handles the elmah interface within MVC routing (no need to use that axd anymore)
    The problem with that solution (and with all the ones here) is that one way or another the elmah error handler is actually handling the error, ignoring what you might want to set up as a customError tag or through ErrorHandler or your own error handler
    The best solution IMHO is to create a filter that will act at the end of all the other filters and log the events that have been handled already. The elmah module should take care of loging the other errors that are unhandled by the application. This will also allow you to use the health monitor and all the other modules that can be added to asp.net to look at error events

    I wrote this looking with reflector at the ErrorHandler inside elmah.mvc

    public class ElmahMVCErrorFilter : IExceptionFilter
    {
       private static ErrorFilterConfiguration _config;
    
       public void OnException(ExceptionContext context)
       {
           if (context.ExceptionHandled) //The unhandled ones will be picked by the elmah module
           {
               var e = context.Exception;
               var context2 = context.HttpContext.ApplicationInstance.Context;
               //TODO: Add additional variables to context.HttpContext.Request.ServerVariables for both handled and unhandled exceptions
               if ((context2 == null) || (!_RaiseErrorSignal(e, context2) && !_IsFiltered(e, context2)))
               {
                _LogException(e, context2);
               }
           }
       }
    
       private static bool _IsFiltered(System.Exception e, System.Web.HttpContext context)
       {
           if (_config == null)
           {
               _config = (context.GetSection("elmah/errorFilter") as ErrorFilterConfiguration) ?? new ErrorFilterConfiguration();
           }
           var context2 = new ErrorFilterModule.AssertionHelperContext((System.Exception)e, context);
           return _config.Assertion.Test(context2);
       }
    
       private static void _LogException(System.Exception e, System.Web.HttpContext context)
       {
           ErrorLog.GetDefault((System.Web.HttpContext)context).Log(new Elmah.Error((System.Exception)e, (System.Web.HttpContext)context));
       }
    
    
       private static bool _RaiseErrorSignal(System.Exception e, System.Web.HttpContext context)
       {
           var signal = ErrorSignal.FromContext((System.Web.HttpContext)context);
           if (signal == null)
           {
               return false;
           }
           signal.Raise((System.Exception)e, (System.Web.HttpContext)context);
           return true;
       }
    }
    

    Now, in your filter config you want to do something like this:

        public static void RegisterGlobalFilters(GlobalFilterCollection filters)
        {
            //These filters should go at the end of the pipeline, add all error handlers before
            filters.Add(new ElmahMVCErrorFilter());
        }
    

    Notice that I left a comment there to remind people that if they want to add a global filter that will actually handle the exception it should go BEFORE this last filter, otherwise you run into the case where the unhandled exception will be ignored by the ElmahMVCErrorFilter because it hasn't been handled and it should be loged by the Elmah module but then the next filter marks the exception as handled and the module ignores it, resulting on the exception never making it into elmah.

    Now, make sure the appsettings for elmah in your webconfig look something like this:

    <add key="elmah.mvc.disableHandler" value="false" /> <!-- This handles elmah controller pages, if disabled elmah pages will not work -->
    <add key="elmah.mvc.disableHandleErrorFilter" value="true" /> <!-- This uses the default filter for elmah, set to disabled to use our own -->
    <add key="elmah.mvc.requiresAuthentication" value="false" /> <!-- Manages authentication for elmah pages -->
    <add key="elmah.mvc.allowedRoles" value="*" /> <!-- Manages authentication for elmah pages -->
    <add key="elmah.mvc.route" value="errortracking" /> <!-- Base route for elmah pages -->
    

    The important one here is "elmah.mvc.disableHandleErrorFilter", if this is false it will use the handler inside elmah.mvc that will actually handle the exception by using the default HandleErrorHandler that will ignore your customError settings

    This setup allows you to set your own ErrorHandler tags in classes and views, while still loging those errors through the ElmahMVCErrorFilter, adding a customError configuration to your web.config through the elmah module, even writing your own Error Handlers. The only thing you need to do is remember to not add any filters that will actually handle the error before the elmah filter we've written. And I forgot to mention: no duplicates in elmah.

    0 讨论(0)
  • 2020-11-22 03:04

    For me it was very important to get email logging working. After some time I discover that this need only 2 lines of code more in Atif example.

    public class HandleErrorWithElmahAttribute : HandleErrorAttribute
    {
        static ElmahMVCMailModule error_mail_log = new ElmahMVCMailModule();
    
        public override void OnException(ExceptionContext context)
        {
            error_mail_log.Init(HttpContext.Current.ApplicationInstance);
            [...]
        }
        [...]
    }
    

    I hope this will help someone :)

    0 讨论(0)
  • 2020-11-22 03:09

    You can take the code above and go one step further by introducing a custom controller factory that injects the HandleErrorWithElmah attribute into every controller.

    For more infomation check out my blog series on logging in MVC. The first article covers getting Elmah set up and running for MVC.

    There is a link to downloadable code at the end of the article. Hope that helps.

    http://dotnetdarren.wordpress.com/

    0 讨论(0)
  • 2020-11-22 03:10

    Sorry, but I think the accepted answer is an overkill. All you need to do is this:

    public class ElmahHandledErrorLoggerFilter : IExceptionFilter
    {
        public void OnException (ExceptionContext context)
        {
            // Log only handled exceptions, because all other will be caught by ELMAH anyway.
            if (context.ExceptionHandled)
                ErrorSignal.FromCurrentContext().Raise(context.Exception);
        }
    }
    

    and then register it (order is important) in Global.asax.cs:

    public static void RegisterGlobalFilters (GlobalFilterCollection filters)
    {
        filters.Add(new ElmahHandledErrorLoggerFilter());
        filters.Add(new HandleErrorAttribute());
    }
    
    0 讨论(0)
提交回复
热议问题