How to Enable Custom Activity Tracing in WCF?

You can define your own application-specific or service-specific activities that you want to trace. To do this, you define a TraceSource in your code and pass a name for the source. You can then use this source name in your WCF configuration file and add a trace listener to it.

As your code runs, you can notify your TraceSource of events and information that you want to make available to trace listeners. For example, the trace information could be a message that details the method running, the parameters passed, and the return value. You can also create an activity identifier to identify activities that are associated with your trace information. Tools like Service Trace Viewer can use these activity identifications to correlate related events.

The following code examples show how you can enable custom activity tracing.

[Visual C#]

TraceSource ts = new TraceSource("bankServiceTraceSource");

 

Guid oldActivityID = Trace.CorrelationManager.ActivityId;

Guid newActivityID = Guid.NewGuid();

ts.TraceTransfer(0, "transfer", newActivityID);

Trace.CorrelationManager.ActivityId = newActivityID; ts.TraceEvent(TraceEventType.Start, 0, "Add request");

 

string msg = String.Format("Tried to withdraw {0} from "

   + "account {1}", amount, account);

ts.TraceInformation(msg);

 

ts.TraceTransfer(0, "transfer", oldActivityID);

ts.TraceEvent(TraceEventType.Stop, 0, "Add request");

Trace.CorrelationManager.ActivityId = oldActivityID;

 

For more information about custom tracing, see Emitting User-Code Traces.