SimpleLogger.SimpleLog.GetCaller C# (CSharp) Method

GetCaller() private static method

Detects the method that was calling the log method
The method is walking up the frames in the stack trace until the first method outside SimpleLog is reached. When log calls to SimpleLog are wrapped in an application, this may still not be the method where logging was called initially (e.g. when an exception occurred and has been logged). In that case set framesToSkip accordingly to get outside the wrapper method(s).
private static GetCaller ( int framesToSkip ) : string
framesToSkip int How many frames to skip when detecting the calling method. This is useful when log calls to are wrapped in an application. Default is 0.
return string
        private static string GetCaller(int framesToSkip = 0)
        {
            string result = string.Empty;

            int i = 1;

            while(true)
            {
                // Walk up the stack trace ...
                var stackFrame = new StackFrame(i++);
                MethodBase methodBase = stackFrame.GetMethod();
                if(methodBase == null)
                    break;

                // Here we're at the end - nomally we should never get that far
                Type declaringType = methodBase.DeclaringType;
                if(declaringType == null)
                    break;

                // Get class name and method of the current stack frame
                result = string.Format("{0}.{1}", declaringType.FullName, methodBase.Name);

                // Here, we're at the first method outside of SimpleLog class.
                // This is the method that called the log method. We're done unless it is
                // specified to skip additional frames and go further up the stack trace.
                if(declaringType != typeof(SimpleLog) && --framesToSkip < 0)
                    break;
            }

            return result;
        }