Common method to log method entry and method exit

Generic methods to log the method entry and method exit in your logger component.


namespace My_Samples
{
    using System;
    using System.Diagnostics;
    using System.Reflection;

    class Program
    {
        static void Main(string[] args)
        {
            MyLogUtility.LogMethodEntry();
            // do some operation
            MyLogUtility.LogMethodExit();
            Console.ReadLine();
        }

    }

    public static class MyLogUtility
    {
        public static void LogMethodEntry()
        {
            StackTrace callStack = new StackTrace();
            StackFrame frame = callStack.GetFrame(1);
            MethodBase method = frame.GetMethod();
            Console.WriteLine(">>>" + method.DeclaringType.FullName + "->" + method.ToString());
        }

        public static void LogMethodExit()
        {
            StackTrace callStack = new StackTrace();
            StackFrame frame = callStack.GetFrame(1);
            MethodBase method = frame.GetMethod();
            Console.WriteLine("<<<" + method.DeclaringType.FullName + "->" + method.ToString());
        }
    }
}

StackTrace – This is an order collection of StackFrames. StackTrace.GetFrame(int index) retrieves corresponding stack frame. This class is in the System.Diagnostics namespace.

StackFrame – This class provides the stack frame information. This class contains couple of useful diagnostics information like, GetFileName, GetFileLineNumber, GetMethod and etc..

StackFrame.GetMethod() –This method retrieves MethodBase instance.

MethodBase – This class provides information about methods and constructor. This class is in the System.Reflection namespace. The DeclaringType property gives the class that declares this method.

No comments:

Post a Comment