Logging entry and exit of methods along with parameters automagically?

前端 未结 7 577
遇见更好的自我
遇见更好的自我 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 05:14

    Functions

    To expand on Jared's answer, avoiding code repetition and including options for arguments:

    private static void LogEnterExit(bool isEnter = true, params object[] args)
    {
        StackTrace trace = new StackTrace(true);  // need `true` for getting file and line info
        if (trace.FrameCount > 2)
        {
            string ns = trace.GetFrame(2).GetMethod().DeclaringType.Namespace;
            string typeName = trace.GetFrame(2).GetMethod().DeclaringType.Name;
            string args_string = args.Length == 0 ? "" : "\narguments: [" + args.Aggregate((current, next) => string.Format("{0},{1};", current, next))+"]";
            Console.WriteLine("{0} {1}.{2}.{3}{4}", isEnter ? "Entering" : "Exiting", ns, typeName, trace.GetFrame(2).GetMethod().Name, args_string );
        }
    }
    
    static void LogEnter(params object[] args)
    {
        LogEnterExit(true, args);
    }
    
    static void LogExit(params object[] args)
    {
        LogEnterExit(false, args);
    }
    

    Usage

    static void DoSomething(string arg1)
    {
        LogEnter(arg1);
        Console.WriteLine("Executing DoSomething");
        LogExit();
    }
    

    Output

    In the console, this would be the output if DoSomething were run with "blah" as arg1

    Entering Program.DoSomething
    arguments: [blah]
    Executing DoSomething
    Exiting Program.DoSomething
    
    0 讨论(0)
提交回复
热议问题