【问题标题】:ELMAH Log handled exceptionsELMAH 日志处理异常
【发布时间】:2018-10-14 01:22:12
【问题描述】:

我正在使用 ELMAH 尝试并记录处理的异常(发生在 try catch 中的异常)。但是,我无法让 ELMAH 记录在 try catch 中发生的任何异常。

这是我的行动:

    [ValidateAntiForgeryToken]       
    public async Task<ActionResult> Login(LoginViewModel model) {

        try {
            throw new Exception("Log me elmah");
        }
        catch (Exception e) {
            ModelState.AddModelError("", "Something unexpected happened, please try again.");
            return View(model);
        }
    }

我已经听从了这里的建议: https://docs.elmah.io/elmah-and-custom-errors/ 和这里:How to get ELMAH to work with ASP.NET MVC [HandleError] attribute?

但我的ElmahExceptionLogger 只会因未处理的异常而被触发。

这是我的ElmahExceptionLogger

public class ElmahExceptionLogger : IExceptionFilter {
    public void OnException(ExceptionContext filterContext) {
        if (filterContext.ExceptionHandled) {
            ErrorSignal.FromCurrentContext().Raise(filterContext.Exception);
        }
    }
}

这是我的global.asax

  public class MvcApplication : System.Web.HttpApplication
    {
        protected void Application_Start()
        {
            AreaRegistration.RegisterAllAreas();
            FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
            RouteConfig.RegisterRoutes(RouteTable.Routes);
            BundleConfig.RegisterBundles(BundleTable.Bundles);        
        }      
    }

这是我的注册全局过滤器方法:

 public class FilterConfig {
        public static void RegisterGlobalFilters(GlobalFilterCollection filters) {
            filters.Add(new ElmahExceptionLogger());
            filters.Add(new HandleErrorAttribute());



            /*Append no cache to all actions in all controllers so we don't cache any pages, I dont particularly like it because it means an increased server load
            However there are reasons to this; The first being data gets updated regularly and we want users to have the most up-to-date data
            And also you can press back after logging out to get to the cached page before. It can be overridden per action if needed */
            filters.Add(new OutputCacheAttribute {
                VaryByParam = "*",
                Duration = 0,
                NoStore = true
            });
        }
    }

有谁知道如何让 ELMAH 在尝试捕获中记录我的异常?

【问题讨论】:

    标签: c# asp.net-mvc error-handling elmah


    【解决方案1】:

    当然,它只会被未处理的异常触发。这些过滤器只针对允许冒泡的错误运行(意思是,未处理)。如果您想记录已处理的异常,则需要将 ErrorSignal.FromCurrentContext().Raise() 逻辑放入您的 catch 块中。

    catch (Exception e)
    {
        ModelState.AddModelError("", "Something unexpected happened, please try again.");
        ErrorSignal.FromCurrentContext().Raise(e);
        return View(model);
    }
    

    如果您发现自己经常这样做,那么我建议您关闭使用 Elmah。 Elmah 不是一个通用的日志框架,它适用于未处理的错误。最好使用SerilogNlog 等日志系统,然后将这些日志记录到Seq 等专用系统。

    【讨论】:

    • 我明白这一点,但我想知道是否有一种自动记录未处理异常的方法
    • @Andrew 你把这两者搞混了。这不是一个未处理的异常,因为你没有让它冒泡。你已经处理好了。
    • 对不起,这是一个错字。我的意思是有一种方法可以自动记录处理的异常。但我猜不是,谢谢您的回复
    • @Andrew 不,不会有,因为您已经捕获异常。如果您正在捕获它,那么将为它运行的唯一代码将在 catch 块内,除非您选择重新抛出它。重新扔掉你已经处理好的东西并不是一个好主意。
    • @Andrew 我在我的问题底部添加了一段关于记录这类事情的更好方法的段落。
    【解决方案2】:

    虽然这里不是完全“自动”,但我采取的一种方法至少可以使 Try-Catch 块中的日志记录更容易。

    我首先为 Exception 类创建了一个扩展:

        Imports Elmah
        Imports System
        Imports System.Web
        Imports System.Runtime.CompilerServices
    
    
    Public Module ElmahExtension
    
        <Extension()>
        Public Sub LogToElmah(ex As Exception)
    
    
            If HttpContext.Current Is Nothing Then
    
                ErrorLog.GetDefault(Nothing).Log(New [Error](ex))
                Dim req = New HttpRequest(String.Empty, "https://YOURWEBSITE", Nothing)
                Dim res = New HttpResponse(Nothing)
            Else
                ErrorSignal.FromCurrentContext().Raise(ex)
                ErrorLog.GetDefault(HttpContext.Current).Log(New [Error](ex))
            End If
        End Sub
    End Module
    

    要使用它,您可以这样做:

       Try
    
          YOUR CODE HERE
    
      Catch
          ex.LogToElmah()
      End Try
    

    这会将异常对象传递给 ELMAH 并记录错误。

    所以不是很自动化,但更容易。特别是,如果您使用 ReSharper 之类的工具来创建包含“ex.LogToELMAH”的代码快捷方式。

    【讨论】:

      猜你喜欢
      • 2014-03-18
      • 2014-10-28
      • 2010-10-23
      • 2011-12-05
      • 1970-01-01
      • 1970-01-01
      • 2011-03-01
      • 2012-04-13
      相关资源
      最近更新 更多