I basically want to write a customer logger/tracer which also logs the class and method name of the method that calls the logger/tracer. This should be fast so that it does not affect the performance of the application, strongly typed and clean. Does anyone have good ideas?
Here are the few I had but I worry about performance due to reflection:
StackTrace/StackFrame (too much overhead?)
MethodInfo.GetCurrentMethod() (still too slow? and not very clean)
pass method as delegate (C# can do that implicitly and I have access to the MethodInfo, but not very clean)
I appreciate anyone's comments.
UPDATE:
I liked the cleanless of StackFrame so I asked a more specific question here with regards to StackFrame's performance and I got some really good response including performance tests. It turns out that MethodInfo.GetCurrentMethod()
is the fastest (takes about 1 microsecond on my computer) and new StackFrame(1)
can be requested on demand (takes about 15-20 microseconds on my computer). I threw out the method as delegate option since it's too messy when the method has several parameters.
CONCLUSION:
I've looked at all the options and the best is to write a custom plug-in for PostSharp which injects the method name as string in MSIL during compilation when applying a custom attribute like [Trace]
to it. It's the fastest and most maintainable option in my opinion. This even enables a lot more things like passing the parameters names and arguments without any kind of reflection and catching and logging exceptions automatically. This my related question for more information.