How to use ELMAH to manually log errors

Omu picture Omu · Sep 16, 2011 · Viewed 95k times · Source

Is it possible to do the following using ELMAH?

logger.Log(" something");

I'm doing something like this:

try 
{
    // Code that might throw an exception 
}
catch(Exception ex)
{
    // I need to log error here...
}

This exception will not be automatically logged by ELMAH, because it was handled.

Answer

Andrey Kamaev picture Andrey Kamaev · Sep 16, 2011

Direct log writing method, working since ELMAH 1.0:

try 
{
    some code 
}
catch(Exception ex)
{
    Elmah.ErrorLog.GetDefault(HttpContext.Current).Log(new Elmah.Error(ex));
}

ELMAH 1.2 introduces a more flexible API:

try 
{
    some code 
}
catch(Exception ex)
{
    Elmah.ErrorSignal.FromCurrentContext().Raise(ex);
}

There is a difference between the two solutions:

  • Raise method applies ELMAH filtering rules to the exception. Log method does not.
  • Raise is subscription based and is able to log one exception into the several loggers.