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


    关于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 专业开发: 气象软件、监狱网上购物系统、两法衔接平台
  • 相关阅读:
    WCF后续之旅(3): WCF Service Mode Layer 的中枢—Dispatcher
    .Net 2.0对文件传输协议(FTP)操作(上传,下载,新建,删除,FTP间传送文件等)
    我的WCF之旅(13):创建基于MSMQ的Responsive Service
    .net程序集强名称签名实践
    WCF后续之旅(8):通过WCF Extension 实现与MS Enterprise Library Policy Injection Application Block 的集成
    .Net 2.0对文件传输协议(FTP)操作(上传,下载,新建,删除,FTP间传送文件等) 2
    WCF后续之旅(6): 通过WCF Extension实现Context信息的传递
    SilverlightCatchWcfError
    WCF后续之旅(7):通过WCF Extension实现和Enterprise Library Unity Container的集成
    WCF后续之旅(4):WCF Extension Point 概览
  • 原文地址:https://www.cnblogs.com/sucsy/p/1826091.html
Copyright © 2020-2023  润新知