通过函数栈空间获取当前调用函数

本文介绍了一种在日志模块中记录调用函数堆栈的方法。通过分析StackTrace,可以获取到调用日志函数的具体位置,包括类型名和方法名,从而帮助开发者更好地定位问题。

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

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

1)软件运行的业务数据

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

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

ExpandedBlockStart.gif 获取调用函数
 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)))

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

转载于:https://www.cnblogs.com/sucsy/archive/2010/09/14/1826091.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值