it is possible to get stacktrace of methods calls inside call method?

梦想的初衷 提交于 2019-12-26 18:24:18

问题


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.



来源:https://stackoverflow.com/questions/33334490/it-is-possible-to-get-stacktrace-of-methods-calls-inside-call-method

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!