Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Best way to log errors in WCF

Tags:

c#

.net

logging

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.

like image 224
Kye Avatar asked Dec 18 '09 12:12

Kye


2 Answers

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.

like image 183
fspirit Avatar answered Oct 01 '22 13:10

fspirit


WCF can be configured to output traces for process milestones across all components of the applications, such as operation calls, code exceptions, warnings and other significant processing events.

The following is an app.config example to enable tracing.

<configuration>
  <system.diagnostics>
    <sources>
      <source name="System.ServiceModel" switchValue="Warning" propagateActivity="true" >
        <listeners>
          <add name="xml"/>
        </listeners>
      </source>

      <source name="myUserTraceSource" switchValue="Warning, ActivityTracing">
        <listeners>
          <add name="xml"/>
        </listeners>
      </source>
    </sources>

    <sharedListeners>
      <add name="xml" 
           type="System.Diagnostics.XmlWriterTraceListener" 
           initializeData="TraceLog.svclog" />
    </sharedListeners>

  </system.diagnostics>
</configuration>

You can read more about WCF Tracing from MSDN: Configuring Tracing.

Microsoft provides a Service Trace Viewer Tool to read .svclog files.

Apart from tracing, you may also want to consider using log4net for in-application logging.

like image 34
Daniel Vassallo Avatar answered Oct 01 '22 13:10

Daniel Vassallo