Over a million developers have joined DZone.

Logging All Unhandled Exceptions In WCF With Log4Net

·

Scientific studies have shown that all applications contain a number of bugs. It is naïve to think that your applications would be bug free. When bugs occur is important that the necessary information gets logged to reproduce and fix the issues.

Assuring that all unhandled exceptions get logged in crucial. If you don’t know all the unhandled exceptions you will be blind for what happens in the production environment impacting your end-users. WCF produces the necessary hook to know when an unhandled exception has occurred in your services: the IErrorHandler. In this short article, I will demonstrate a simple implementation that logs these exceptions with Log4Net.

The most important component in this example is ofcourse the error handler implementation itself. The method “HandleError” gets called for every unhandled exception by the WCF stack. This method has to indicate with its return value if it has “handled” the exception or if it remains “unhandled”. In our implementation we just log it with Log4Net and indicate to WCF that it remains unhandled and has to pass the stack further.

public class Log4NetErrorHandler : IErrorHandler
{
    private static readonly ILog log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);

    public bool HandleError(Exception error)
    {
        log.Error("An unexpected has occurred.", error);

        return false; // Exception has to pass the stack further
    }

    public void ProvideFault(Exception error, MessageVersion version, ref Message fault)
    {
    }
}

The only thing that remains now is to hook this IErrorHandler implementation into the WCF stack. To do this, we must implement a new service behavior. Below you can find the necessary code.

public class Log4NetServiceBehavior : IServiceBehavior
{
    public void AddBindingParameters(ServiceDescription serviceDescription, ServiceHostBase serviceHostBase, Collection endpoints, BindingParameterCollection bindingParameters)
    {
    }

    public void ApplyDispatchBehavior(ServiceDescription serviceDescription, ServiceHostBase serviceHostBase)
    {
        IErrorHandler errorHandler = new Log4NetErrorHandler();

        foreach (ChannelDispatcher channelDispatcher in serviceHostBase.ChannelDispatchers)
        {
            channelDispatcher.ErrorHandlers.Add(errorHandler);
        }
    }

    public void Validate(ServiceDescription serviceDescription, ServiceHostBase serviceHostBase)
    {
    }
}

Next we must implement a Behavior Extension Element to this into WCF stack using the web.config or the app.config

public class Log4NetBehaviorExtensionElement : BehaviorExtensionElement
{
    public override Type BehaviorType
    {
        get { return typeof (Log4NetServiceBehavior); }
    }

    protected override object CreateBehavior()
    {
        return new Log4NetServiceBehavior();
    }
}

Now we can declare in the config that WCF must use our custom service behavior extension.

<system.serviceModel>
<services>
<!-- We define our WCF Services ... -->
</service>
</services>

<behaviors>
<serviceBehaviors>
<behavior>
<log4net />
</behavior>
</serviceBehaviors>
</behaviors>

<extensions>
<behaviorExtensions>
<add name="log4net"
type="MyProject.Log4NetBehaviorExtensionElement, MyProject, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null" />
</behaviorExtensions>
</extensions>
</system.serviceModel>
Topics:

The best of DZone straight to your inbox.

SEE AN EXAMPLE
Please provide a valid email address.

Thanks for subscribing!

Awesome! Check your inbox to verify your email so you can start receiving the latest in tech news and resources.
Subscribe

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}