Sunday 3 April 2011

Dot.Net: Calling Method Name for Logging

Question:
I want to log the name of the method that called me. How do I do this in c#?
How do I get the name of the caller method at a given execution point in dot.net?



Answer:
You can use the StackFrame and StackTrace objects.

By default, a new StackFrame in a context is the current StackFrame

And the StackTrace gives you access to the caller hierarchy.

If you are in a debug build configuration you'll have all the information you want.
Attention! : In release mode (in prod) you'll have much less information and some method calls might have disappeared, due to compiler optimization.
Msdn says: "StackTrace might not report as many method calls as expected, because of code transformations that occur during optimization."

Here is an example
using System.Diagnostics;
using System.Reflection;

...

    private void Call_GetTheCaller()
    {
        // call another method
        GetTheCaller();
    }

    private void GetTheCaller()
    {
        StackFrame sFrame = new StackFrame();
        MethodBase methodInfo = sFrame.GetMethod();
        Console.WriteLine(methodInfo.Name);
        // writes : GetTheCaller

        StackTrace sTrace = new StackTrace();
        StackFrame sFrame2 = sTrace.GetFrame(1);
        MethodBase methodInfo2 = sFrame2.GetMethod();

        Console.WriteLine(methodInfo2.Name);
        // writes : Call_GetTheCaller
    }
...

No comments: