Kye Kye - 5 months ago 71
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.


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.