ELMAH - Exception Logging without having HttpContext

前端 未结 4 1343
野的像风
野的像风 2020-12-13 03:40

I tried this solution with Elmah.XmlFileErrorLog but I\'m getting following exception

System.ArgumentNullException was unhandled by user code
  Message=\"Val         


        
相关标签:
4条回答
  • 2020-12-13 04:07

    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

    0 讨论(0)
  • 2020-12-13 04:08

    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));
            }
        }
    }
    
    0 讨论(0)
  • 2020-12-13 04:12

    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);
    
    0 讨论(0)
  • 2020-12-13 04:24

    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

    0 讨论(0)
提交回复
热议问题