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 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");
     }
}

I think the best approach here would be to use code injection technique to inject tracing method calls to get details of method and log it. I have explained this approach in an article here: http://www.codeproject.com/Articles/445858/Tracing-with-Code-Injection

Idea is to not try and get currently invoking method information at runtime but to inject code at the start of method body to call logging method on TraceSource and pass method details. Hope that helps.

链接地址: http://www.djcxy.com/p/52400.html

上一篇: 实体框架6从存储过程获取完整的返回值

下一篇: 如何获取从.net中发送跟踪日志的方法和类的名称