ELMAH - Exception Logging without having HttpContext

匆匆过客 提交于 2019-11-28 17:24:42
IsmailS

I'm answering my own question.

I tried adding following in my web.config

<system.serviceModel>
  <serviceHostingEnvironment aspNetCompatibilityEnabled="true" />
</system.serviceModel>

Also decorated my Service with following attribute

[AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Required)]    
public class CalculatorService : ICalculatorSession    
{
    // Implement calculator service methods
 }

Still no use. Then I got the solution here by which you can use Elmah without HTTPContext. i.e. log errors by writing

Elmah.ErrorLog.GetDefault(null).Log(new Error(ex));

instead of

Elmah.ErrorSignal.FromCurrentContext().Raise(error);

Thanks everyone, here is my ErrorHelper class I came up with to manually log errors on websites and in WCF services, windows services, etc:

    public static class ErrorHelper
{
    /// <summary>
    /// Manually log an exception to Elmah.  This is very useful for the agents that try/catch all the errors.
    /// 
    /// In order for this to work elmah must be setup in the web.config/app.config file
    /// </summary>
    /// <param name="ex"></param>
    public static void LogErrorManually(Exception ex)
    {
        if (HttpContext.Current != null)//website is logging the error
        {                
            var elmahCon = Elmah.ErrorSignal.FromCurrentContext();
            elmahCon.Raise(ex);
        }
        else//non website, probably an agent
        {                
            var elmahCon = Elmah.ErrorLog.GetDefault(null);
            elmahCon.Log(new Elmah.Error(ex));
        }
    }
}

The only stable solution I could find is to remove the web.config attribute and use the service behavior attribute they use in Exception Logging for WCF Services using ELMAH

Are you running this code within ASP.NET? Seems like the HttpContext is null and this is causing the ELmah code to throw the exception -the method Elmah.ErrorSignal.FromCurrentContext() would pass HttpContext.Current from what I remember (been awhile since looked into it) to the Elmah.ErrorSignal.FromContext(HttpContext context) method and this seems to be null, which would not normally be the case in Asp.Net hosted stuff.

Another possibility is that this is occuring outside a request to the server so the HttpContext might be null

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!