How to Trace all local variables when an exception occurs

前端 未结 4 1497
面向向阳花
面向向阳花 2020-12-28 09:27

any generic way to trace/log values of all local variables when an exception occurs in a method? (in C# 3)

4条回答
  •  暗喜
    暗喜 (楼主)
    2020-12-28 10:08

    Answer: Using PostSharp (Policy Injection), XTraceMethodBoundary attribute, override OnException . this logs all the method input and return parameters types and values. I modified PostSharp to add a simple method to log parameters. not perfect but good enough

    private static void TraceMethodArguments(MethodExecutionEventArgs eventArgs)
    {
        object[] parameters = eventArgs.GetReadOnlyArgumentArray();
    
        if (parameters != null)
        {
            string paramValue = null;
            foreach (object p in parameters)
            {
                Type _type = p.GetType();
                if (_type == typeof(string) || _type == typeof(int) || _type == typeof(double) || _type == typeof(decimal))
                {
                    paramValue = (string)p;
                }
                else if (_type == typeof(XmlDocument))
                {
                    paramValue = ((XmlDocument)p).OuterXml;
                }
                else
                { //try to serialize
                    try
                    {
                        XmlSerializer _serializer = new XmlSerializer(p.GetType());
                        StringWriter _strWriter = new StringWriter();
    
                        _serializer.Serialize(_strWriter, p);
                        paramValue = _strWriter.ToString();
                    }
                    catch
                    {
                        paramValue = "Unable to Serialize Parameter";
                    }
                }
                Trace.TraceInformation("[" + Process.GetCurrentProcess().Id + "-" + Thread.CurrentThread.ManagedThreadId.ToString() + "]" + " Parameter: " + paramValue);
            }
        }
    }
    

提交回复
热议问题