Question from my brother Brent:
Is there a way to determine what file and method called my function? I have a logging object that I would like to be able to automatically add the function, file, and line number of the caller.
Also, I'd like to automatically generate debug output when a function begins and exits
there are a couple options here...
If you want to profile, there are several profilers (Rational, Numega, etc.) and they are are managed aware. Given that you want this for logging, etc, there are even more options, read on...
- You can use context bound objects and produce a somewhat heavy, but really cool framework for auto-logging, which can give you the begin/exit outputs
- You can use the StackTrace class to get file, line, and function name information at any point during execution
The caution I would give about either of these is performance. ContextBoundObject has some significant performance implication, as does using the StackTrace class. In addition, the StackTrace class will only give file and line information if the PDB is available.
Since C# doesn't support macros (a good thing, btw), you are faced with either hand coding a lot of Debug.Write*(...) method calls, or living without this feature.
Maybe this is something we should think about adding to .NET? you could imagine something that plugs into the JIT and lets you compile in pre/post code for any method... ouch, and API into the JIT - that sounds scary. Maybe we shouldn't consider this :)