tags:

views:

431

answers:

5

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.

A: 

I would go with number 1. Mainly because of reduced overhead over number 3 and number 2 should just be a no-no.

Granted you still want to log to something say like a file or event manager. But I personnally would use log4net for it since it's a bit lighter than all the entlib stuff.

Joshua Cauble
A: 

It might be worth your while to check out log4net. There is a good tutorial here on CodeProject.

Hope this helps, Best regards, Tom.

tommieb75
I prefer using the .NET tracing - it's already built into the .NET framework, and is one less dependency on an external component
marc_s
I also liked this log4net tutorial. Very comprehensive. http://www.beefycode.com/category/log4net.aspx
ram
+2  A: 

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.

Daniel Vassallo
if you already set up .NET tracing, why not use that functionality for application logging, too?? Removes another of those pesky dependencies on external components, and it works quite well indeed
marc_s
@marc_s: Thank you for the suggestion. However, would you still use .NET tracing for logging events other than errors: like 'access hits'? ... and would you apply the same reasoning for the live environment?
Daniel Vassallo
+1  A: 

If you are asking for logging framework ELMAH is also a good option to consider. If you dont like to litter your code with try/catch around each method, you can try using AOP frameworks which would give you the ability to handle exceptions by marking the method with Attributes

ram
We've had success using AoP via the Unity Interface Interceptor. Bit of a learning curve, especially around exception handling, but we now have a great reusable code block that logs all of our WCF I/O at info level (via log4net)
Richard Ev
nice answer Richard !! I will add it to my "to learn" list
ram
+2  A: 

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.

fspirit
I prefer using the .NET tracing - it's already built into the .NET framework, and is one less dependency on an external component.
marc_s
@marc_s. Since .NET 1.1 i got used to log4net, since it offered much more flexibility than standard .NET tracing. One small and open-source (it means you can fix bugs there if you find any) lib dependency is not a big deal.
fspirit