Elmah 在 Asp.Net MVC 应用程序启动时记录错误日志

4

可能重复:
elmah:没有HttpContext的异常?

Global.asax

public class MvcApplication : System.Web.HttpApplication
{
    protected void Application_Start()
    {
        AreaRegistration.RegisterAllAreas();
        RegisterGlobalFilters(GlobalFilters.Filters);
        RegisterRoutes(RouteTable.Routes);
        throw new Exception("TEST");
    }


    // ... other usual methods
}

Elmah没有记录异常。

我在这里做了很多初始化和配置工作,如果出现任何问题,获取错误日志非常重要。

不确定为什么它不起作用,但可能与MVC生命周期有关 - 或许在这个阶段没有HttpContext?有没有办法通过Elmah记录错误?


这篇文章涵盖了与https://dev59.com/9nI95IYBdhLWcg3w3yJU相同的领域,那里有比这里更好的答案。 - Alexander Garden
1个回答

1

关于一件事,你绝对是对的,HttpContext.CurrentApplication_Start中不存在,这可能是Elmah无法记录该方法中的错误的问题之一。

但是,如果在Application_Start中出现异常,那么你面临的问题比Elmah不记录异常更大。你的Application_Start方法应该是完美无缺的,或者如果不是,它需要被编写成在开发环境中失败,这样你就可以在推送到生产环境之前发现问题。如果是间歇性的异常,我建议将有问题的代码放在其他地方。

更新

根据你的评论,也许这对你有用。它还具有在每个请求中检查是否第一次失败的额外好处。

protected void Application_BeginRequest(object sender, EventArgs args)
{
  CheckConfiguration();
}

private static readonly object ConfigurationLockObject = new object();
private void CheckConfiguration()
{
  /** Lock Bypass **/
  if (IsConfigured()) 
  {
    return;
  }

  // The lock ensures the configuration only gets called one at a time.
  lock (ConfigurationLockObject)
  {
    // Must check for configuration again, just in case multiple threads had hit the lock
    if (!IsConfigured())
    {
      try
      {
        // Configuration Code
      }
      catch (Exception exception)
      {
        Log.Error("Exception Occurred", exception);
      }
    }
  }
}

2
Application_Start 是我的 IOC 容器初始化的地方,需要从配置文件中读取。我同意这是一个可能引发异常的糟糕位置,但我想不到其他解决方法。 - fearofawhackplanet

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接