it is possible to get stacktrace of methods calls

2019-09-22 07:58发布

问题:

I want to add more info to the logger at the call method level, and i need to know if exist possibility to get StackTrace of methods calls inside call method.

UPDATE: The purpose of this is to draw the flow of all methods called until the certain step inside call method.

EXAMPLE:

public class Type1
{
    internal string method2_T1() {
        return new Type2().method1_T2();
    }        
}


public class Type2
{
    public string method1_T2()
    {
        return "Type2.method1_T2";
    }       
}



static void Main(string[] args)
{            
     string t = new Type1().method2_T1();

      LogNow();

        ....
}

and the result to obtain, when I call LogNow(), are:

StackTrace of method2_T1()

...

Thanks

回答1:

It's pretty easy:

var stackTrace = new StackTrace(true);
var traceToLog = stackTrace.ToString();

The true argument says to include the file info.



回答2:

Todd Sprang's answer is good as the actual answer, but be aware that the stack trace will change in unpredictable ways when you move to a RELEASE build, or use async/await. Don't rely programatically on the answers because you may come unstuck when you put the code into production.



回答3:

If you want to know the direct caller of a particular function, in a way Microsoft recommend, there's the useful trick using the [CallerMemberName], [CallerFilePath], and [CallerLineNumber] attributes. Mark up optional parameters like so;

public void LogWithCallerInfo(
    string message,
    [CallerMemberName] string memberName = "Caller",
    [CallerFilePath] string sourceFilePath = "File",
    [CallerLineNumber] int sourceLineNumber = 0)
    {
        WriteProgressMessage(..., memberName, sourceFilePath, sourceLineNumber);
    }

and call like this;

LogWithCallerInfo("my message");

The three optional parameters will be replaced with the appropriate call info.