Monday 28 September 2009

WCF Tracing with Activities

One of the nice features of Windows Communication Foundation (WCF) is that it can generate an excess of trace information that can help us identify issues with our services. All you need to do is turn the tracing on through the app.config like so....

name="System.ServiceModel"
switchValue="Information">
name="traceListener"
type="System.Diagnostics.XmlWriterTraceListener"
initializeData= "c:\log\Traces.svclog" />
Microsoft even provide a handy tool called Service Trace Viewer Tool (SvcTraceViewer.exe) that can be used to view the trace information that WCF produces.

However, if you have ever looked at one of these traces you will have noticed that it can be difficult to sieve through and find the service call(s) that you are interested in. It becomes especially difficult if the service calls other services. Wading through all this tracing information is time consuming and it can be very frustrating.

Fortunately WCF provides a mechanism called Activities that allow us to correlate related trace information.

Where these Activities start and stop are defined by the developer in code. They can also be propagated across service boundaries and can also be linked together with other related activities.

So, what do you need to do in order to use Activities in your tracing? They are quite simple to use, all you need to do is assign an activity id to the correlation manager. This is a GUID value and is assigned as follows:

Trace.CorrelationManager.ActivityId = Guid.NewGuid();

Now, all the trace messages that are fired after this will be included in this Activity. However, in order for this to appear in the trace log we need to add ActivityTracing to the switchValue of the diagnostics section of the app.config.

name="System.ServiceModel"
switchValue="Information ActivityTracing"
propagateActivity="true">
name="traceListener"
type="System.Diagnostics.XmlWriterTraceListener"
initializeData= "c:\log\Traces.svclog" />
Also, if we want the ActivityId to be passed from one service to another, we can set the propagateActivity attribute to True. This is useful if we are starting the activity in one service operations that is then calling other services operations to achieve it's goals. With propagateActivity set to true, all of the trace information from these services for this particular call would be grouped together.

No comments: