In my previous post I mentioned that I have been using both Open Rasta and ELMAH so this post explains how to make them play nicely together. To get started you will need to set up both libraries in your project as per their documentation, then follow along below.
Open Rasta actually attempts to handle its errors rather than letting them fall out to ASP.Net’s normal unhandled exception events. This means that ELMAH never hears about them and doesn’t log them by default. Fortunately both Open Rasta and ELMAH provide easy hooks for us to easily set this up.
Sometimes you have exceptions which don’t represent a complete application meltdown but you would like to know about anyway. ELMAH has an API set up for just such an occasion:
ErrorSignal
.FromCurrentContext()
.Raise(ex);
This simple call grabs the current ELMAH setup from HttpContext and passes it any exception we want.
Open Rasta logs exceptions and lots of other useful information while it is running. By default this information is logged to .Net trace output but we’re going to replace that. Here’s a simple logger that will do the job:
public class ElmahLogger : OpenRasta.Diagnostics.ILogger
{
public void WriteException(Exception ex)
}
public void WriteDebug(string message, params object[] f) { }
public void WriteWarning(string message, params object[] f) { }
public void WriteError(string message, params object[] f) { }
public void WriteInfo(string message, params object[] f) { }
public class OperationContext : IDisposable
public void Dispose() { }
public IDisposable Operation(object source, string name)
return new OperationContext();
The important lines are in the WriteException method at the top. You can use the rest of the methods to gather a full log from Open Rasta’s pipeline to include in the exception details if you want.
Since Open Rasta has a simple dependency injection container built right in, telling it to use our logger simply requires adding these lines to your normal configuration:
ResourceSpace.Uses
.CustomDependency<ILogger, ElmahLogger>
(DependencyLifetime.Singleton);
That wasn’t so bad now was it?