2017-12-28 1 views
0

예외가 발생한 클래스에서 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 클래스해야 기대하는 반면

: ConvertAIToPNG 방법 : DAMFileOperation

내가 알고, 나는 바퀴를 다시 발명하고 있습니다. Log4Net/Elmah를 사용할 수 있습니다. 그러나 여전히, 나는 이유/해결책을 찾아 내고 싶다. 또한 웹 애플리케이션/Windows 앱이 아닌 웹 사이트에서이 코드를 사용하고 있습니다.. 그러나 나는 모든 사례를 고려하여보다 일반적인 것으로 만들려고 노력했습니다.

미리 감사드립니다.

답변

0

감사합니다. 수정되었습니다. 그것은 간단한 수정이었다.

var methodBase = new StackFrame(1).GetMethod(); 
    appLog.ClassName = methodBase.DeclaringType. FullName; 
    appLog.MethodName = methodBase.Name; 
으로

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

를 대체

관련 문제