Cyberiafreak

"Fortunate are those who take the first steps.” ― Paulo Coelho

What is so special about CorrelationManager Class?

It groups the traces that are part of a logical transaction. It can be nested. Two things important from this classes are,
1)ActivityId-Gets or sets the id for a global activity-GUID
2)LogicalOperationStack-Gets the logical operation stack from the call context.

Ex: Correlated traces by ASP.NET request/response in the log.

It provide a way to store logical operation identity(Guid) in a thread context and automatically tag each trace event generated by the thread with the Guid.

This class, recently helped us in solving one of the logging related problem.

I mean we required a transactional logging such a way that, it can be grouped in log viewer for easy understanding. Let say, an event raised and launched few threads which has got each of their log statements with some variables- with this class we can group them with Guid..so we can easily understand the navigated path as like in stack trace while debugging.

private static void SampleWithThreading()
{
thread1 = new Thread(SampleMethod1) { Name = “T1” };
thread2 = new Thread(SampleMethod1) { Name = “T2” };

thread3 = new Thread(SampleMethod2) { Name = “T3” };
thread4 = new Thread(SampleMethod2) { Name = “T4” };

Trace.CorrelationManager.StartLogicalOperation(“Operation1”);
Trace.CorrelationManager.ActivityId = Guid.NewGuid();
string logString = “(Operation1)Transaction 1 started with Guid:-” + Trace.CorrelationManager.ActivityId;
Console.WriteLine(logString);
traceSource.TraceData(TraceEventType.Information, 1, logString);

thread1.Start(100);
thread2.Start(300);

Trace.CorrelationManager.StartLogicalOperation(“Operation2”);
Trace.CorrelationManager.ActivityId = Guid.NewGuid();
logString = “(Operation2)Transaction 2 started with Guid:-” + Trace.CorrelationManager.ActivityId;
Console.WriteLine(logString);
traceSource.TraceData(TraceEventType.Information, 1, logString);

thread3.Start(200);
thread4.Start(400);

Thread.Sleep(2000);

Trace.CorrelationManager.StopLogicalOperation();
}

Read more from src: http://msdn.microsoft.com/en-us/library/system.diagnostics.correlationmanager.aspx

Advertisements

December 9, 2011 - Posted by | Uncategorized

No comments yet.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: