通过函数栈空间获取当前调用函数 南京酷得软件

关于StackTrace的基础可以参见浅析StackTrace顽强的灰太狼)。

我们在设计日志模块时通常会记录两种信息:

1)软件运行的业务数据

2)软件运行的技术参数(如当前调用的函数堆栈)。

 一下通过一下方法可以获取当前调用的函数:

获取调用函数
 1 private static string GetCaller()
 2         {
 3             StackTrace stackTrace = new StackTrace();           // get call stack
 4             StackFrame[] stackFrames = stackTrace.GetFrames();  // get method calls (frames)
 5 
 6             int i = 1;
 7             for (; i < stackFrames.Length; i++)
 8             {
 9                 StackFrame stackFrame = stackFrames[i];
10                 if (stackFrame.GetMethod() != null)
11                 {
12                     string typeName = stackFrame.GetMethod().ReflectedType == null ? stackFrame.GetMethod().Name : stackFrame.GetMethod().ReflectedType.Name;
13                     string methodName = stackFrame.GetMethod().Name;
14                     if ("LogHelper".Equals(typeName) && ("WriteMessage".Equals(methodName) || "WriteLog".Equals(methodName)))
15                     {
16                         i++;
17                     }
18                     else
19                     {
20                         if (stackFrames.Length >= i + 1)
21                         {
22                             stackFrame = stackFrames[i];
23                             return stackFrame.GetMethod().ReflectedType == null ? stackFrame.GetMethod().Name : stackFrame.GetMethod().ReflectedType.Name + "." + stackFrame.GetMethod().Name;
24                         }
25                         else
26                         {
27                             break;
28                         }
29                     }
30                 }
31             }
32 
33             return "";
34         }

其中:

if ("LogHelper".Equals(typeName) && ("WriteMessage".Equals(methodName) || "WriteLog".Equals(methodName)))

是用于判断是否为当前日志模块的方法,如果是则忽略。

公司网站: http://www.codersoft.cn 专业开发: 气象软件、监狱网上购物系统、两法衔接平台
原文地址:https://www.cnblogs.com/sucsy/p/1826091.html