WCF Error Handling using IErrorHandler and log4net
Apr 11, 2012
3 minute read
When its comes to managing and supporting WCF services, like any software, having insight into erroronous situtions is essential. There are several ways to go about this that are specific to WCF, such as enabling a trace listener for example. A more customisable option involves fleshing out an IErrorHandler. As put by MSDN, provides the necessary hooks to run custom error processing logic.
Allows an implementer to control the fault message returned to the caller and optionally perform custom error processing such as logging.
To the code. Couple of quick notes and assumptions about it. The IErrorHandler concrete implementation uses Apache’s log4net logging library. I am dealing with only IIS hosted WCF services so can rely on ASP.NET pipeline events to fire, such as the ApplicationStart event in global.asax to do initalisation work such as setting up a log4net logger.
The extension element definition, so consumers can bind against the behavior in their respective system.servicemodel configuration section.
The behavior itself. Note how the Log4NetErrorHandler is added to teh ErrorHandlers collection for every channel dispatcher that exists.
The IErrorHandler log4net logger.
Instructs log4net where/how to pickup its XML configuration.
Specific to each WCF service. Two key sections to highlight are the log4net configuration (which uses an AdoNetAppender to log into a SQL Server database), and the WCF (System.ServiceModel) chunk that binds the custom IErrorHandler against the service. Configuring log4net specifically to each service provides the flexibility of controlling the IErrorHandler and its underlying logging configuration, such as specific log4net appenders (e.g. Windows eventlog, rolling file, SQL server, whatever), as a side effect “bleeds” its implementation out to its consumers (breaking the DRY principle). A preferred option could have the log4net IErrorHandler reach out to a single, server-wide configuration file (e.g. log4net.config) that defined a unifed logging configuration that would apply to all services.