elmah: exceptions without HttpContext?

萝らか妹 提交于 2019-11-26 19:49:16

问题


I spawn a thread on Application_Start and would like to log exceptions. There is no Context/HttpContext/HttpContext.Current, so how might I get it to log?

At the moment, it does not catch any exception in my threads and if I write ErrorSignal.FromCurrentContext().Raise(ex); I get an error about context cannot be null.

Maybe I can create a dummy HttpContext but somehow I don't think that will work well.

-edit- I tried ErrorSignal.Get(new HttpApplication()).Raise(ex); and it doesn't seem to pick up that exception.


回答1:


Make sure you set your application name in web.config

<errorLog type="Elmah.SqlErrorLog, Elmah" 
          connectionStringName="nibWeb" 
          applicationName="Nib.Services" />

and then

ErrorLog.GetDefault(null).Log(new Error(error));

will work




回答2:


I wasn't using <errorLog> as in Brendan Carey's answer because I was only in-memory logging. Nevertheless, his command worked great in my case without naming the application:

Elmah.ErrorLog.GetDefault(null).Log(new Elmah.Error(new Exception("The application has done something.")));

I DID have to recompile Elmah with .NET 4.0, because of an error about needing System.Web.Abstractions 3.5.0.0. My compiled-for-.NET 4.0 fork is here if anyone wants it (also strong naming):

http://code.google.com/r/scottstafford-elmah/




回答3:


For my application, I saved this.Context.ApplicationInstance in Application_Start so that I can call Elmah.ErrorSignal.Get with the saved instance. With the ErrorSignal, I could then Raise. This goes through all the email filters.

Below is the code. I use FluentScheduler to

public class Global : HttpApplication {
    void Application_Start(object sender, EventArgs e) {

        var application = Context.ApplicationInstance;
        FluentScheduler.TaskManager.UnobservedTaskException +=
            (FluentScheduler.Model.TaskExceptionInformation i, UnhandledExceptionEventArgs a) =>
                Elmah.ErrorSignal.Get(application).Raise(i.Task.Exception);

    }
}



回答4:


I added a solution to: Using ELMAH in a console application that adds ability to send email, tweets and filter in addition to logging.



来源:https://stackoverflow.com/questions/2108404/elmah-exceptions-without-httpcontext

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