Thursday, July 30, 2009

 

Using a static class for logging exceptions using ELMAH

If you have used Elmah for logging exceptions in your Visual Studio projects, you must have used the following syntax in the try..catch blocks

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

Or if you want to log a custom message you do something like


try
{
...
}
catch
{
ErrorSignal.FromCurrentContext().Raise(new Elmah.ApplicationException(Message));
}

Or also include the exception object with the message like this


try
{
....
}
catch(Exception ex)
{
ErrorSignal.FromCurrentContext().Raise(new Elmah.ApplicationException(Message,ex));
}

As you can see this is a lot of text to be put in each try..catch block, so to make it look a little bit nice I made a static class that looks like this


/// <summary>
/// This class logs exception in ELMAH
/// </summary>
public static class Error
{
/// <summary>
/// Logs the exception in ELMAH with a custom message
/// </summary>
/// <param name="Message">Custom message</param>
/// <param name="ex">Exception object</param>
public static void Log(string Message, Exception ex)
{
ErrorSignal.FromCurrentContext().Raise(new Elmah.ApplicationException(Message,ex));
}

/// <summary>
/// Logs the message in ELMAH
/// </summary>
/// <param name="Message">Custom message</param>
public static void Log(string Message)
{
ErrorSignal.FromCurrentContext().Raise(new Elmah.ApplicationException(Message));
}

/// <summary>
/// Logs the exception in ELMAH
/// </summary>
/// <param name="ex"></param>
public static void Log(Exception ex)
{
ErrorSignal.FromCurrentContext().Raise(ex);
}
}

Now the try..catch block looks like this


try
{
.....
}
catch (Exception ex)
{
Error.Log("this is a custom error",ex);
}

Take it away here

Labels: ,


This page is powered by Blogger. Isn't yours?