其他分享
首页 > 其他分享> > .NET使用StackTrace获取方法调用信息

.NET使用StackTrace获取方法调用信息

作者:互联网

原文 https://www.cnblogs.com/netry/p/dotnet-stacktrace-stackframe.html

在日常工作中,偶尔需要调查一些诡异的问题,而业务代码经过长时间的演化,很可能已经变得错综复杂,流程、分支众多,如果能在关键方法的日志里添加上调用者的信息,将对定位问题非常有帮助。

介绍
StackTrace, 位于 System.Diagnostics 命名空间下,名字很直观,它代表一个方法调用的跟踪堆栈,里面存放着按顺序排列的栈帧对象(StackFrame),每当发生一次调用,就会压入一个栈帧;而一个栈帧,则拥有本次调用的各种信息,除了MethodBase,还包括所在的文件名、行、列等。

演示
下面代码演示了如何获取调用者的方法名、所在文件、行号、列号等信息。

public static string GetCaller()
{
StackTrace st = new StackTrace(skipFrames: 1, fNeedFileInfo: true);
StackFrame[] sfArray = st.GetFrames();

   return string.Join(" -> ",
        sfArray.Select(r =>
            $"{r.GetMethod().Name} in {r.GetFileName()} line:{r.GetFileLineNumber()} column:{r.GetFileColumnNumber()}"));

}
第一帧是 GetCaller本身,所以跳过;fNeedFileInfo设置成 true,否则调用者所在文件等信息会为空。
简单创建个控制台程序并添加几个类模拟一下,输出如下:

UpdateOrder in G:\examples\MethodCall2\ClassLevel6.cs line:11 column:8 ->
Level5Method in G:\examples\MethodCall2\ClassLevel5.cs line:8 column:9 ->
Level4Method in G:\examples\MethodCall2\ClassLevel4.cs line:10 column:9 ->
Level3Method in G:\examples\MethodCall2\ClassLevel3.cs line:10 column:9 ->
Level2Method in G:\examples\MethodCall2\ClassLevel2.cs line:10 column:9 ->
InternalMethod in G:\examples\MethodCall2\ClassLevel1.cs line:12 column:13 ->
Main in G:\examples\MethodCall2\Program.cs line:18 column:17
可以看到因为StackTrace是个栈结构(FILO),所以打印出来的顺序也是由近及远的。

链接
StackTrace Class https://docs.microsoft.com/en-us/dotnet/api/system.diagnostics.stacktrace?view=net-6.0
StackFrame Class https://docs.microsoft.com/en-us/dotnet/api/system.diagnostics.stackframe?view=net-6.0

标签:StackTrace,调用,column,examples,cs,NET,MethodCall2,line
来源: https://www.cnblogs.com/wang2650/p/16685215.html