mardi 23 février 2016

How to get name of method and class from where trace logs are sent in .net

I wrote my own custom trace listener and now I'm using TraceSource object to call all the custom methods that I have overridden from virtual methods of base class TraceListener namely various overloads of TraceData(..), TraceEvent(..) and TraceTransfer(..) etc.

While using TraceSource object to log traces I won't be directly calling any of my custom methods (on my custom listener) rather I would grab an instance of TraceSource and will call (on it) TraceSource object's own methods such as TraceData(..),TraceEvent(..) and TraceInformation(..) and these methods will internally call my custom methods.

Now the thing is that I need to find the name of the class and method where the trace messages or logs are coming from. I'm searching all over the internet and found something over here C# how to get the name of the current method from code

But it still is not giving me sufficient feedback as to how would I avoid compiler optimizations in production environment ( As the link given above says at one point that these attributes are needed all the way up the stack trace to avoid method in-lining and tail-recursion in production) but I can't put attributes such as

     [MethodImpl(MethodImplOptions.NoInlining)]

on TraceSource class' methods (as they are already out the box in-built functions which I have no control over) though I can do the same for my custom methods but only doing that won't solve my problem. Having said that, another problem that I'm facing (attributes issue apart). How can I send name of the class (in my case XYZ class) and the method(MyMethod) to my custom trace listener methods (since MyMethod is not directly calling my custom methods only the TraceSource's TraceData(...) is internally calling one of my custom methods), capture this info inside of my custom methods and then do whatever I want to do with that info.

 public class XYZ
 {
     static readonly TraceSource source = new TraceSource("somesource");
     public void MyMethod()
     {  
        source.TraceData(eventType.Error,1, "This is an error message");
     }
}





Aucun commentaire:

Enregistrer un commentaire