views:

56

answers:

3

Background: I have written a generic logging library in .NET 3.5. Basically the developer needs to call the Begin() method at the beginning of their method and the End() method at the end of it. These methods do not take a parameter - the library uses the stacktrace to figure out where it came from. The library has a collection that keeps track of the call stack and writes out the elapsed time of each method.

This works really well and I'm happy with it.

But now we want to add it to the server. When multiple users are on the system, there is only one log file and the stack traces are lumped together. It's impossible to tell which thread is doing what.

My question is this:

Is there a way to retrieve a unique value from the StackTrace class or an indivdual StackFrame? What about using reflection? I would like to be able to create a seperate file for each user. At the very least, I'd like to be able to tag each line with the unique value so we can filter the file by this value when reviewing traces.

We are using WCF TcpBinding as our server side communication protocol, if that helps. I am looking for a thread id, hashcode, address, something to distinguish where the call stack came from.

Any ideas?

Thanks.

+2  A: 

You could use something associated with the current thread - perhaps the thread id?.

Threads from the thread pool get reused, so you would see the id's repeated throughout the log file, but for the lifetime of a Begin/End pair it would uniquely tag a single user.

adrianbanks
Yep - `Thread.CurrentThread.ManagedThreadId` should do it nicely.
Pavel Minaev
This worked for me. In addition, I found the MethodBase.MethodHandle property which I am using in combination with the ManagedThreadId. Thanks!
msawtatn
A: 

To get the user account under which the current thread is running, you can use WindowsIdentity.GetCurrent().

Pavel Minaev
You can also use `Thread.CurrentPrincipal.Identity`.
adrianbanks
A: 

If you used some form of Aspect Oriented Programming (like Postsharp) you might find a better, declarative way to get the information you need. Thread.CurrentThread.ManagedThreadId would give you a reference for the thread running the code at the time, but all your developers would have to do do is apply an attribute to a method, rather than calling Begin() and End() for every method.

Neil Barnwell