【问题标题】:Getting class/method name that called a common function获取调用通用函数的类/方法名
【发布时间】:2012-07-31 16:58:28
【问题描述】:

我不太确定如何最好地提出这个问题,所以请随时编辑...

我有一个“实用程序”类,其中包含在我的应用程序中使用的常用功能。我的一种方法记录这样的异常:

internal static void logExeption(Type typeOfClass, string methodName, Exception exeption )
 {
   //Do some logging here
 }

然后,每当我捕获到这样的异常时,我想在整个应用程序中调用它:

try{
  //perform some action
}
catch(Exception ex)
{
Utils.logExeption(this.GetType(), System.Reflection.MethodBase.GetCurrentMethod().Name, ex);
 }

我想知道是否有一种方法可以避免传入前两个参数,而只需找出在 logException 方法中引发异常的类/方法的上下文。从长远来看,这将使我的事情变得更清洁。

【问题讨论】:

    标签: c# .net visual-studio-2010 logging typeof


    【解决方案1】:

    所以你要确定调用对象和函数。虽然不推荐,但可以实现。使用 System.Diagnostics.StackTrace 遍历堆栈;然后将适当的 StackFrame 提升一级。然后通过在该 StackFrame 上使用 GetMethod() 确定哪个方法是调用者。请注意,构建堆栈跟踪可能是一项代价高昂的操作,并且您的方法的调用者可能会掩盖事物的真正来源。

    StackFrame frame = new StackFrame(1);
    MethodBase method = frame.GetMethod();
    string message = String.Format("{0}.{1} : {2}",
    method.DeclaringType.FullName, method.Name, message);
    Console.WriteLine(message);
    

    【讨论】:

      【解决方案2】:

      请注意frame.GetMethod().DeclaringType 可以返回null:以前我只在使用NLog logger (GetCurrentClassLogger) 的发布版本 的应用程序中遇到了这个问题。具体情况记不清了。对了,是known issue

      Apache log4net 中有一个有趣的技巧,它允许检测调用者信息(类、方法等)。

      请看:

      1. LocationInfo 类 (source) - 调用者位置信息的内部表示。

         public class LocationInfo
         {
             ...
        
             public LocationInfo(Type callerStackBoundaryDeclaringType)
             {
                 // Here is the trick. See the implementation details here.
             }
        
             ...
         }
        
      2. LogImpl 类 (source) - 记录器实现类 - ILogger 接口的包装器 - 达到目的不能子类化

         public class LogImpl : LoggerWrapperImpl, ILog
         {
             ...
             public LogImpl(ILogger logger) : base(logger)
             {
                 ...
             }
        
             /// <summary>
             /// The fully qualified name of this declaring type not the type of any subclass.
             /// </summary>
             private readonly static Type ThisDeclaringType = typeof(LogImpl);
        
             virtual public void Error(object message, Exception exception)
             {
                 Logger.Log(ThisDeclaringType, m_levelError, message, exception);
             }
        
             ...
         }
        

      【讨论】:

        【解决方案3】:

        您可以使用StackTrace Class。请参阅与您的问题非常相似的示例。

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2019-04-08
          • 1970-01-01
          • 2015-12-19
          • 2022-12-10
          • 1970-01-01
          • 1970-01-01
          • 2015-11-13
          • 1970-01-01
          相关资源
          最近更新 更多