Kye Kye - 1 year ago 146
C# Question

Best way to log errors in WCF

What's the best way to catch and log errors when developing a WCF service layer, and why?

I can think of three ways,

1) Manual try/catches around each method.

2) Leave the responsibility to the WCF engine.

3) Use a third party library such as Enterprise Library Policy Injection/Logging.

Answer Source

I would implement custom IErrorHandler and use log4net

[AttributeUsage (AttributeTargets.Interface)]
public class ErrorPolicyBehaviorAttribute : Attribute, IContractBehavior, IErrorHandler
    private ILog m_logger;

    #region IErrorHandler

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

    public bool HandleError (Exception error)
        m_logger.Error (error.Message, error);
        return true;


    #region IContractBehavior

    public void ApplyDispatchBehavior (ContractDescription contractDescription, ServiceEndpoint endpoint, DispatchRuntime dispatchRuntime)
        ...init logger
        ......Add this class to a list of dispatchRuntime.ChannelDispatcher.ErrorHandlers...


This class also implements IContractBehavior, so you can use it as Attribute on your service contracts.

public interface IYourServiceContract
{ }

log4net is quite flexible, so you can log what you need and when you need.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download