Home > C#, WCF > Logging all unhandled exceptions in WCF with Log4Net

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 now 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 now 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>
About these ads
Categories: C#, WCF
  1. September 3, 2013 at 06:52

    Great idea! I am going to give it a bash on my latest project and see how it works out. This should help catch those hidden errors that do nasty things like faulting channels.

  1. No trackbacks yet.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

Follow

Get every new post delivered to your Inbox.

Join 28 other followers

%d bloggers like this: