从异常中获取不正确的类和方法名称

问题描述 投票:0回答:1

我试图从发生异常的类中获取Class和MethodName。请参阅以下代码:

  [MethodImpl(MethodImplOptions.NoInlining)]
    public void Log(object obj, LogTypes logType, int userId = 0, string userName = "", [CallerFilePath] string sourceFilePath = "",[CallerMemberName] string methodName = "")
    {
        var appLog = new ApplicationLog();
        try
        {
            appLog.UserId = userId;
            appLog.UserName = userName;
            appLog.InstanceName = ConfigurationSettingsHelper.InstanceName;
            appLog.ProjectName = HostingEnvironment.IsHosted ? HostingEnvironment.ApplicationHost.GetSiteName() : Assembly.GetCallingAssembly().GetName().Name;
            appLog.LoggedOn = DateTime.UtcNow;
            appLog.FilePath = sourceFilePath;
            if (logType==LogTypes.Exception)
            {
                if (obj is Exception ex)
                {
                    appLog.LogType = 1;
                    appLog.LogDetails = ex.ToString();
                    if (ex.TargetSite.DeclaringType != null)
                        appLog.ClassName = ex.TargetSite.DeclaringType.FullName;
                    appLog.MethodName = ex.TargetSite.Name;
                    appLog.Message = ex.Message;
                }
            }
            else
            {
                appLog.LogType = 2;
                var reflectedType = new StackFrame(1).GetMethod().ReflectedType;
                if (reflectedType != null)
                    appLog.ClassName = reflectedType.FullName;
                appLog.MethodName = methodName;
                appLog.LogDetails = obj is string ? obj.ToString() : "NA-Not a valid logging.";
            }
        }
        catch (Exception ex)
        {
            //In case of unhandled exceptions.Try logging internal exception once.
            //If failed, pass by silently.
            try
            {
                appLog = new ApplicationLog
                {
                    UserId = userId,
                    UserName = userName,
                    FilePath = new StackFrame(1).GetFileName(),
                    Message = ex.Message,
                    InstanceName = ConfigurationSettingsHelper.InstanceName,
                    ProjectName = Assembly.GetCallingAssembly().GetName().Name,
                    LoggedOn = DateTime.UtcNow,
                    LogType = 1,
                    LogDetails = ex.ToString()
                };
                if (ex.TargetSite.DeclaringType != null)
                    appLog.ClassName = ex.TargetSite.DeclaringType.FullName;
                appLog.MethodName = ex.TargetSite.Name;
            }
            finally
            {
                HttpWebMethods.PostAsync(ConfigurationSettingsHelper.LoggerApiBaseAddress,
                    ConfigurationSettingsHelper.SaveLogEndpoint, appLog);
            } // intentionally eating exception}
        }
        finally
        {
            HttpWebMethods.PostAsync(ConfigurationSettingsHelper.LoggerApiBaseAddress,
                ConfigurationSettingsHelper.SaveLogEndpoint, appLog);
        }
    }

但上面的代码捕获了错误的类和方法名称。请参阅以下例外情况。

System.FormatException: Input string was not in a correct format.
   at System.Number.StringToNumber(String str, NumberStyles options, NumberBuffer& number, NumberFormatInfo info, Boolean parseDecimal)
   at System.Number.ParseInt32(String s, NumberStyles style, NumberFormatInfo info)
   at System.Convert.ToInt32(String value)
   at Common.ConvertAIToPNG.DAMFileOperation(String fsGUIDFolder, Int32 fiUserID, String fsInputFileName, String& fsOutPutFileName) 
   in c:\Main\PDM\App_code\common\ConvertAIToPNG.cs:line 70
   at DAMFilesUploader.UploadFile(HttpContext context) in c:\Main\PDM\Uploader\DAMFilesUploader.ashx:line 82

我正在捕获并记录此异常以及它发生的类名和方法名称。但在这里我得到了

类:System.Number |方法:StringToNumber

然而,预期应该是Class:ConvertAIToPNG方法:DAMFileOperation

我知道,我正在重新发明轮子。我可以使用Log4Net / Elmah。但是,我仍想弄清楚原因/解决方案。此外,我在我的网站中使用此代码而不是在WebApp / Windows应用程序中。但我已经考虑了所有情况并试图使其更通用。

提前致谢。

c# .net system.reflection
1个回答
0
投票

谢谢,我得到了修复。这是一个简单的修复。

更换

 if (ex.TargetSite.DeclaringType != null)
     appLog.ClassName = ex.TargetSite.DeclaringType.FullName;
     appLog.MethodName = ex.TargetSite.Name;

有了这个

   var methodBase = new StackFrame(1).GetMethod();
   appLog.ClassName = methodBase.DeclaringType. FullName;
   appLog.MethodName = methodBase.Name;
© www.soinside.com 2019 - 2024. All rights reserved.