Wednesday, 18 September 2013

Linking multiple TraceSource events with CorrelationManager

Linking multiple TraceSource events with CorrelationManager

I am developing a web service in C# with .NET WebAPI and I would like to
log multiple events for every request, into Windows event log. Since the
service runs in a multithreaded model and will receive hundreds or
requests per second, I need to be able to group log entries by requests,
so that I can see all the entries for a failed request for example.
The plan is to generate a unique Id (Guid) for every request and log event
with a severity level (Verbose/Information/Error/Warning/Critical)
including the Id in every log entry, so that I can group the events.
After trying with NLog, I started looking into
System.Diagnostics.TraceSource in combination with
System.Diagnostics.Trace.CorrelationManager.ActivityId, following articles
found online, many here on SO. Logging works but I'm stuck on two
problems.
My web.config:
<system.diagnostics>
<sources>
<source name="My.App" switchValue="Verbose, ActivityTracing">
<listeners>
<add name="eventlogListener" />
</listeners>
</source>
</sources>
<sharedListeners>
<add name="eventlogListener"
type="System.Diagnostics.EventLogTraceListener"
initializeData="MyAppCategory" />
</sharedListeners>
</system.diagnostics>
Problem 1
If I use TraceTransfer I can specify the ActivityId (which is
automatically appended to the message) but I cannot specify the event
level (e.g. TraceEventType.Error)
If I use TraceEvent I can specify the level but not the ActivityId, and
the Activity Id does not appear anywhere
Is there a way to have both level and activity id in a log event ?
Problem 2
I would like to see the ActivityId in the "Correlation Id" column of the
event viewer, so that I can group events. I've seen some applications
storing a Guid there, but I haven't found any documentation on how to
achieve the same in C#/.NET. I noticed that TraceEvent accepts a object[]
args parameter, for which I have not found any example though.
Could anyone point me to some docs or provide a working example ?
Thank you

No comments:

Post a Comment