How to use ELMAH to manually log errors

C#Exception HandlingElmahError Logging

C# Problem Overview


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.

C# Solutions


Solution 1 - C#

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.

Solution 2 - C#

I'd recommend wrapping the call to Elmah in a simple wrapper class of your own.

using Elmah;

public static class ErrorLog
{
    /// <summary>
    /// Log error to Elmah
    /// </summary>
    public static void LogError(Exception ex, string contextualMessage=null)
    {
        try
        {
            // log error to Elmah
            if (contextualMessage != null) 
            {
                // log exception with contextual information that's visible when 
                // clicking on the error in the Elmah log
                var annotatedException = new Exception(contextualMessage, ex); 
                ErrorSignal.FromCurrentContext().Raise(annotatedException, HttpContext.Current);
            }
            else 
            {
                ErrorSignal.FromCurrentContext().Raise(ex, HttpContext.Current);
            }

            // send errors to ErrorWS (my own legacy service)
            // using (ErrorWSSoapClient client = new ErrorWSSoapClient())
            // {
            //    client.LogErrors(...);
            // }
        }
        catch (Exception)
        {
            // uh oh! just keep going
        }
    }
}

Then just call it whenever you need to log an error.

try {
   ...
} 
catch (Exception ex) 
{
    // log this and continue
    ErrorLog.LogError(ex, "Error sending email for order " + orderID);
}

This has the following benefits:

  • You don't need to remember this slightly archaic syntax of the Elmah call
  • If you have many DLLs you don't need to reference Elmah Core from every single one - and just put this in your own 'System' DLL.
  • If you ever need to do any special handling or just want to put in a breakpoint to debug errors you have it all one place.
  • If you ever move away from Elmah you can just change one place.
  • If you have legacy error logging you want to retain (I just happen to have a simple error logging mechanism that's tied into some UIs that I dont immediately have time to remove).

Note: I've added a 'contextualMessage' property for contextual information. You can omit this if you prefer but I find it very useful. Elmah automatically unwraps exceptions so the underlying exception will still be reported in the log but the contextualMessage will be visible when you click on it.

Solution 3 - C#

You can use the Elmah.ErrorSignal() method to log an issue without raising an exception.

try
{
    // Some code
}
catch(Exception ex)
{
    // Log error
    Elmah.ErrorSignal.FromCurrentContext().Raise(ex);

    // Continue
}

Solution 4 - C#

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

Solution 5 - C#

Yes, it is possible. ELMAH was designed to intercept unhandled exceptions. However you can signal an exception to ELMAH via the ErrorSignal class. Those exceptions are not thrown (don't bubble up), but are only sent out to ELMAH (and to subscribers of the Raise event of the ErrorSignal class).

A small example:

protected void ThrowExceptionAndSignalElmah()
{
    ErrorSignal.FromCurrentContext().Raise(new NotSupportedException());
}

Solution 6 - C#

I was looking to do this same thing in a thread I had started to queue mail from within my MVC4 application, as such I did not have the HttpContext available when an exception was raised. To do this I ended up with the following based on this question and another answer found on here: https://stackoverflow.com/questions/2108404/elmah-exceptions-without-httpcontext/2196594#2196594

In the config file I specified an application name:

<elmah>
    <security allowRemoteAccess="false" />
    <errorLog type="Elmah.SqlErrorLog, Elmah" connectionStringName="ELMAH" applicationName="myApplication"/>   
</elmah>

Then in code (like the answer provided above, but without the HttpContext) you can pass null instead of an HttpContext:

ThreadPool.QueueUserWorkItem(t => {
     try {
         ...
         mySmtpClient.Send(message);
     } catch (SomeException e) {
         Elmah.ErrorLog.GetDefault(null).Log(new Elmah.Error(e));
     }
 });

Solution 7 - C#

I am on ASP.NET core and I use ElmahCore.

To manually log errors with HttpContext (in controller) simply write:

using ElmahCore;
...
HttpContext.RiseError(new Exception("Your Exception"));

In another part of your application without HttpContext:

using ElmahCore;
...
ElmahExtensions.RiseError(new Exception("Your Exception"));

Solution 8 - C#

Sometimes CurrentHttpContext may not be available.

Define

public class ElmahLogger : ILogger
{
    public void LogError(Exception ex, string contextualMessage = null, bool withinHttpContext = true)
    {
        try
        {
            var exc = contextualMessage == null 
                      ? ex 
                      : new ContextualElmahException(contextualMessage, ex);
            if (withinHttpContext)
                ErrorSignal.FromCurrentContext().Raise(exc);
            else
                ErrorLog.GetDefault(null).Log(new Error(exc));
        }
        catch { }
    }
}

Use

public class MyClass
{
    readonly ILogger _logger;

    public MyClass(ILogger logger)
    {
        _logger = logger;
    }

    public void MethodOne()
    {
        try
        {

        }
        catch (Exception ex)
        {
            _logger.LogError(ex, withinHttpContext: false);
        }
    }
}

Solution 9 - C#

I was trying to write custom messages into elmah logs using Signal.FromCurrentContext().Raise(ex); and found that these exceptions are bubbled up, eg:

try
{
    ...
}
catch (Exception ex)
{
    Elmah.ErrorSignal.FromCurrentContext().Raise(ex);
    // this will write to the log AND throw the exception
}

Besides I don't see how elmah supports different levels of logging - is it possible to switch off verbose logging by a web.config setting?

Solution 10 - C#

Used this line and it works perfectly fine.

 try{
            //Code which may throw an error
    }
    catch(Exception ex){
            ErrorLog.GetDefault(HttpContext.Current).Log(new Elmah.Error(ex));
    }

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionOmuView Question on Stackoverflow
Solution 1 - C#Andrey KamaevView Answer on Stackoverflow
Solution 2 - C#Simon_WeaverView Answer on Stackoverflow
Solution 3 - C#bigtvView Answer on Stackoverflow
Solution 4 - C#Darin DimitrovView Answer on Stackoverflow
Solution 5 - C#Christophe GeersView Answer on Stackoverflow
Solution 6 - C#MatthewView Answer on Stackoverflow
Solution 7 - C#A. MorelView Answer on Stackoverflow
Solution 8 - C#tchelidzeView Answer on Stackoverflow
Solution 9 - C#Valery GavrilovView Answer on Stackoverflow
Solution 10 - C#Prajakta KaleView Answer on Stackoverflow