【问题标题】:Elmah log error in Asp.Net MVC Application_Start [duplicate]Asp.Net MVC Application_Start 中的 Elmah 日志错误 [重复]
【发布时间】:2011-07-13 14:55:11
【问题描述】:

可能重复:
elmah: exceptions without 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在这里记录错误?

【问题讨论】:

标签: asp.net-mvc-3 elmah httpcontext error-logging application-start


【解决方案1】:

您绝对是对的一件事,Application_Start 中不存在HttpContext.Current,这可能是 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);
      }
    }
  }
}

【讨论】:

  • Application_Start 是我的 IOC 容器被初始化的地方,这需要从配置文件中读取。我同意这是一个有潜在异常生成代码的坏地方,但我想不出任何办法。
猜你喜欢
  • 1970-01-01
  • 2019-05-25
  • 2017-03-07
  • 1970-01-01
  • 1970-01-01
  • 2014-10-16
  • 2011-04-18
  • 1970-01-01
  • 2010-10-24
相关资源
最近更新 更多