简体   繁体   English

如何让ELMAH使用ASP.NET MVC [HandleError]属性?

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

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 they occur. 我正在尝试使用ELMAH来记录我的ASP.NET MVC应用程序中的错误,但是当我在控制器上使用[HandleError]属性时,ELMAH在发生错误时不会记录任何错误。

As I am guessing its because ELMAH only logs unhandled errors and the [HandleError] attribute is handling the error so thus no need to log it. 正如我猜测它,因为ELMAH只记录未处理的错误,[HandleError]属性正在处理错误,因此无需记录它。

How do I modify or how would I go about modifying the attribute so ELMAH can know that there was an error and log it.. 我如何修改或如何修改属性,以便ELMAH可以知道有错误并记录它..

Edit: Let me make sure everyone understands, I know I can modify the attribute thats not the question I'm asking... ELMAH gets bypassed when using the handleerror attribute meaning it won't see that there was an error because it was handled already by the attribute... What I am asking is there a way to make ELMAH see the error and log it even though the attribute handled it...I searched around and don't see any methods to call to force it to log the error.... 编辑:让我确保每个人都理解,我知道我可以修改那个不是我问的问题的属性... ELMAH在使用handleerror属性时会被绕过,这意味着它不会看到有错误因为它被处理了已经由属性...我要问的是有一种方法让ELMAH看到错误并记录它即使属性处理它...我搜索周围,没有看到任何方法调用强制它来记录错误....

You can subclass HandleErrorAttribute and override its OnException member (no need to copy) so that it logs the exception with ELMAH and only if the base implementation handles it. 您可以HandleErrorAttribute并覆盖其OnException成员(无需复制),以便它使用ELMAH记录异常,并且仅在基本实现处理它时。 The minimal amount of code you need is as follows: 您需要的最少代码量如下:

using System.Web.Mvc;
using Elmah;

public class HandleErrorAttribute : System.Web.Mvc.HandleErrorAttribute
{
    public override void OnException(ExceptionContext context)
    {
        base.OnException(context);
        if (!context.ExceptionHandled) 
            return;
        var httpContext = context.HttpContext.ApplicationInstance.Context;
        var signal = ErrorSignal.FromContext(httpContext);
        signal.Raise(context.Exception, httpContext);
    }
}

The base implementation is invoked first, giving it a chance to mark the exception as being handled. 首先调用基本实现,使其有机会将异常标记为正在处理。 Only then is the exception signaled. 只有这样才会发出异常信号。 The above code is simple and may cause issues if used in an environment where the HttpContext may not be available, such as testing. 上面的代码很简单,如果在HttpContext可能不可用的环境中使用,例如测试,可能会导致问题。 As a result, you will want code that is that is more defensive (at the cost of being slightly longer): 因此,您将需要更具防御性的代码(代价是稍长一些):

using System.Web;
using System.Web.Mvc;
using Elmah;

public class HandleErrorAttribute : System.Web.Mvc.HandleErrorAttribute
{
    public override void OnException(ExceptionContext context)
    {
        base.OnException(context);
        if (!context.ExceptionHandled       // if unhandled, will be logged anyhow
            || TryRaiseErrorSignal(context) // prefer signaling, if possible
            || IsFiltered(context))         // filtered?
            return;

        LogException(context);
    }

    private static bool TryRaiseErrorSignal(ExceptionContext context)
    {
        var httpContext = GetHttpContextImpl(context.HttpContext);
        if (httpContext == null)
            return false;
        var signal = ErrorSignal.FromContext(httpContext);
        if (signal == null)
            return false;
        signal.Raise(context.Exception, httpContext);
        return true;
    }

    private static bool IsFiltered(ExceptionContext context)
    {
        var config = context.HttpContext.GetSection("elmah/errorFilter")
                        as ErrorFilterConfiguration;

        if (config == null)
            return false;

        var testContext = new ErrorFilterModule.AssertionHelperContext(
                              context.Exception, 
                              GetHttpContextImpl(context.HttpContext));
        return config.Assertion.Test(testContext);
    }

    private static void LogException(ExceptionContext context)
    {
        var httpContext = GetHttpContextImpl(context.HttpContext);
        var error = new Error(context.Exception, httpContext);
        ErrorLog.GetDefault(httpContext).Log(error);
    }

    private static HttpContext GetHttpContextImpl(HttpContextBase context)
    {
        return context.ApplicationInstance.Context;
    }
}

This second version will try to use error signaling from ELMAH first, which involves the fully configured pipeline like logging, mailing, filtering and what have you. 第二个版本将尝试首先使用ELMAH的错误信号 ,这涉及完整配置的管道,如日志记录,邮件,过滤和你有什么。 Failing that, it attempts to see whether the error should be filtered. 如果不这样做,它会尝试查看是否应该过滤错误。 If not, the error is simply logged. 如果没有,则只记录错误。 This implementation does not handle mail notifications. 此实现不处理邮件通知。 If the exception can be signaled then a mail will be sent if configured to do so. 如果可以发出异常信号,那么如果配置了邮件,则会发送邮件。

You may also have to take care that if multiple HandleErrorAttribute instances are in effect then duplicate logging does not occur, but the above two examples should get your started. 您可能还必须注意,如果多个HandleErrorAttribute实例生效,则不会发生重复日志记录,但上述两个示例应该启动。

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: 然后在Global.asax.cs中注册它(顺序很重要):

public static void RegisterGlobalFilters (GlobalFilterCollection filters)
{
    filters.Add(new ElmahHandledErrorLoggerFilter());
    filters.Add(new HandleErrorAttribute());
}

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) 现在NuGet中有一个ELMAH.MVC包,其中包括Atif的改进解决方案以及处理MVC路由中的elmah接口的控制器(不再需要使用该axd)
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 该解决方案(以及此处的所有解决方案)的问题在于,elmah错误处理程序实际上是以某种方式处理错误,忽略了您可能想要设置为customError标记或通过ErrorHandler或您自己的错误处理程序
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. 最好的解决方案是IMHO创建一个过滤器,它将在所有其他过滤器的末尾起作用,并记录已经处理过的事件。 The elmah module should take care of loging the other errors that are unhandled by the application. elmah模块应该注意记录应用程序未处理的其他错误。 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 这还允许您使用运行状况监视器和可添加到asp.net的所有其他模块来查看错误事件

I wrote this looking with reflector at the ErrorHandler inside elmah.mvc 我在elmah.mvc里面的ErrorHandler中用反射器写了这个

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. 请注意,我在那里留下了一个注释,提醒人们如果他们想要添加一个实际处理异常的全局过滤器,它应该在最后一个过滤器之前进行,否则你会遇到ElmahMVCErrorFilter忽略未处理异常的情况,因为它没有被处理,它应该由Elmah模块提供,但是接下来的过滤器将异常标记为已处理,模块忽略它,导致异常从未使它成为elmah。

Now, make sure the appsettings for elmah in your webconfig look something like this: 现在,确保webconfig中的elmah appsettings看起来像这样:

<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 这里重要的是“elmah.mvc.disableHandleErrorFilter”,如果这是假的,它将使用elmah.mvc中的处理程序,该处理程序将使用默认的HandleErrorHandler实际处理异常,该处理程序将忽略您的customError设置

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. 此设置允许您在类和视图中设置自己的ErrorHandler标记,同时仍通过ElmahMVCErrorFilter记录这些错误,通过elmah模块向web.config添加customError配置,甚至编写自己的错误处理程序。 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. 您唯一需要做的就是记住在我们编写的elmah过滤器之前不添加任何实际处理错误的过滤器。 And I forgot to mention: no duplicates in elmah. 我忘了提到:elmah没有重复。

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. 您可以采用上面的代码,并通过引入一个自定义控制器工厂更进一步,该工厂将HandleErrorWithElmah属性注入每个控制器。

For more infomation check out my blog series on logging in MVC. 有关更多信息,请查看我关于登录MVC的博客系列。 The first article covers getting Elmah set up and running for MVC. 第一篇文章介绍了如何让Elmah为MVC设置和运行。

There is a link to downloadable code at the end of the article. 本文末尾有一个可下载代码的链接。 Hope that helps. 希望有所帮助。

http://dotnetdarren.wordpress.com/ http://dotnetdarren.wordpress.com/

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. 一个完全替代的解决方案是不使用MVC HandleErrorAttribute ,而是依赖于Elmah旨在使用的ASP.Net错误处理。

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: 您需要从App_Start \\ FilterConfig(或Global.asax)中删除默认的全局HandleErrorAttribute ,然后在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. 注意,这可以是MVC路由URL,因此上面会在发生错误时重定向到ErrorController.Index操作。

I'm new in ASP.NET MVC. 我是ASP.NET MVC的新手。 I faced the same problem, the following is my workable in my Erorr.vbhtml (it work if you only need to log the error using Elmah log) 我遇到了同样的问题,以下是我的Erorr.vbhtml可行(如果您只需要使用Elmah日志记录错误,它可以工作)

@ModelType System.Web.Mvc.HandleErrorInfo

    @Code
        ViewData("Title") = "Error"
        Dim item As HandleErrorInfo = CType(Model, HandleErrorInfo)
        //To log error with Elmah
        Elmah.ErrorLog.GetDefault(HttpContext.Current).Log(New Elmah.Error(Model.Exception, HttpContext.Current))
    End Code

<h2>
    Sorry, an error occurred while processing your request.<br />

    @item.ActionName<br />
    @item.ControllerName<br />
    @item.Exception.Message
</h2> 

It is simply! 简直就是这样!

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. 经过一段时间后,我发现在Atif示例中只需要2行代码。

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 :) 我希望这会帮助别人:)

This is exactly what I needed for my MVC site configuration! 这正是我的MVC站点配置所需要的!

I added a little modification to the OnException method to handle multiple HandleErrorAttribute instances, as suggested by Atif Aziz: 我添加了一些OnException方法的修改来处理多个HandleErrorAttribute实例,如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. 请记住,如果多个HandleErrorAttribute实例生效,您可能必须注意不会发生重复日志记录。

I simply check context.ExceptionHandled before invoking the base class, just to know if someone else handled the exception before current handler. 我只是在调用基类之前检查context.ExceptionHandled ,只是为了知道其他人是否在当前处理程序之前处理了异常。
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);
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM