Omu Omu - 2 months ago 32
C# Question

How to use ELMAH to manually log errors?

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

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.
Comments