Blog

Integrating ELMAH for a WCF Service

February 5, 2010

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:

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:

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;
    }
}

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

If you and your team want to learn more about how to write maintainable unit tests and get the most out of TDD practices, make sure to have look at our trainings and workshops or check out the books section. Feel free to reach out at infonull@nullprincipal-itnull.be.

Profile picture of Jan Van Ryswyck

Jan Van Ryswyck

Thank you for visiting my blog. I’m a professional software developer since Y2K. A blogger since Y2K+5. Provider of training and coaching in XP practices. Curator of the Awesome Talks list. Past organizer of the European Virtual ALT.NET meetings. Thinking and learning about all kinds of technologies since forever.

Comments

About

Thank you for visiting my website. I’m a professional software developer since Y2K. A blogger since Y2K+5. Author of Writing Maintainable Unit Tests. Provider of training and coaching in XP practices. Curator of the Awesome Talks list. Thinking and learning about all kinds of technologies since forever.

Contact information

(+32) 496 38 00 82

infonull@nullprincipal-itnull.be