Search code examples
c#.netsystem.reflection

Getting incorrect class and method name from exception


I am trying to get the Class and MethodName from the class where exception originated. See the code below:

  [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);
        }
    }

But the above code is capturing wrong class and method name. See an exception below.

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

I am capturing and logging this exception alongwith the class name and method name from where it has occured. But here i am getting

Class: System.Number | Method: StringToNumber

Whereas,expected should be Class:ConvertAIToPNG Method: DAMFileOperation

I knew, I am re-inventing the wheel. I can use Log4Net/Elmah. But still, i want to figure out the reason/solution. Also, I am using this code in my WEBSITE not in WebApp/Windows app.. But i have considered all the cases and tried to make it more generic.

Thanks in Advance.


Solution

  • Thanks , I got the fix. It was a simple fix.

    Replaced

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

    with this

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