Kye Kye - 1 month ago 29
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

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)
        {
        return;
        }

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

    #endregion

    #region IContractBehavior

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

    #endregion
    }

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

[ErrorPolicyBehavior]
public interface IYourServiceContract
{ }

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