Friday, February 05, 2010

Integrating ELMAH for a WCF Service

Peter Cosemans, who is one of my colleagues, found a nice way to integrate ELMAH for a WCF service. ELMAH is an error logging facility for logging unhandled exceptions particularly focused on ASP.NET web applications. There are plenty of sources out there, like this blog post by Scott Hanselman, that describe how to get ELMAH up and running for an ASP.NET web application.

In order to get it working for WCF, you need to provide a custom error handler by implementing the IErrorHandler interface:

public class ElmahErrorHandler : IErrorHandler
{
    public void ProvideFault(Exception error, MessageVersion version, 
                             ref Message fault)
    {
        var dummyRequest = 
            new SimpleWorkerRequest("dummy", "", new StringWriter());
        var context = new HttpContext(dummyRequest);
        
        var elmahLogger = Elmah.ErrorLog.GetDefault(context);
        elmahLogger.Log(new Elmah.Error(error));    
    }

    public Boolean HandleError(Exception error)
    {
        SDExceptionHandler.DoHandle(error);
        return true;
    }
}

This error handler needs to be added to the stack of error handlers. You can do this in a couple of ways, for example by providing a custom attribute that implements IServiceBehavior and then applying this attribute to your service class.

Next you need to add some configuration to your web.config and your all good to go:

<system.web>
    <httpHandlers>
        <add verb="POST,GET,HEAD" 
             path="MyService.Elmah.axd" 
             type="Elmah.ErrorLogPageFactory, Elmah" />
    </httpHandlers>
</system.web>

<elmah>
    <errorLog type="Elmah.XmlFileErrorLog, Elmah" 
              logPath="C:\MyServiceLog\"/>
</elmah>

What’s nice about this approach is that you don’t need to run the WCF service in ASP.NET compatibility mode, which is a major bonus.

Hope this helps

1 comment:

Chandermani said...

I have taken this approach a step further and integrated Azure hosted deployment plus SQL Azure with ELMAH. See my post here

http://chandermani.blogspot.com/2010/11/i-recently-integrated-elmah-error.html