Logging entry and exit of methods along with parameters automagically?

前端 未结 7 592
遇见更好的自我
遇见更好的自我 2021-01-02 04:31

Is there a way for me to add logging so that entering and exiting methods gets logged along with parameters automatically somehow for tracing purposes? How would I do so?

7条回答
  •  旧巷少年郎
    2021-01-02 04:55

    I'm not sure what your actual needs are, but here's a low-rent option. It's not exactly "automatic", but you could use StackTrace to peel off the information you're looking for in a manner that wouldn't demand passing arguments - similar to ckramer's suggestion regarding interception:

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    
    using System.Diagnostics;
    
    namespace TracingSample
    {
        class Program
        {
            static void Main(string[] args)
            {
                DoSomething();
            }
    
            static void DoSomething()
            {
                LogEnter();
    
                Console.WriteLine("Executing DoSomething");
    
                LogExit();
            }
    
            static void LogEnter()
            {
                StackTrace trace = new StackTrace();
                if (trace.FrameCount > 1)
                {
                    string ns = trace.GetFrame(1).GetMethod().DeclaringType.Namespace;
                    string typeName = trace.GetFrame(1).GetMethod().DeclaringType.Name;
                    Console.WriteLine("Entering {0}.{1}.{2}", ns, typeName, trace.GetFrame(1).GetMethod().Name);
                }
            }
    
            static void LogExit()
            {
                StackTrace trace = new StackTrace();
                if (trace.FrameCount > 1)
                {
                    string ns = trace.GetFrame(1).GetMethod().DeclaringType.Namespace;
                    string typeName = trace.GetFrame(1).GetMethod().DeclaringType.Name;
                    Console.WriteLine("Exiting {0}.{1}.{2}", ns, typeName, trace.GetFrame(1).GetMethod().Name);
                }
            }
        }
    }
    

    You could combine something like the above example with inheritance, using a non-virtual public member in the base type to signify the action method, then calling a virtual member to actually do the work:

    public abstract class BaseType
    {
        public void SomeFunction()
        {
    
            LogEnter();
            DoSomeFunction();
            LogExit();
        }
    
        public abstract void DoSomeFunction();
    }
    
    public class SubType : BaseType
    {
        public override void DoSomeFunction()
        {
            // Implementation of SomeFunction logic here...
        }
    }
    

    Again - there's not much "automatic" about this, but it would work on a limited basis if you didn't require instrumentation on every single method invocation.

    Hope this helps.

提交回复
热议问题