如何发生异常时跟踪所有局部变量 [英] How to Trace all local variables when an exception occurs

查看:106
本文介绍了如何发生异常时跟踪所有局部变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

任何通用的方法时异常的方法时跟踪所有局部变量/日志值?
(在C#3)

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

推荐答案

答:使用PostSharp(政策注入),XTraceMethodBoundary属性,覆盖onException的。
本记录所有的方法输入和返回参数类型和值。我修改PostSharp添加一个简单的方法来记录的参数。并不完美,但不够好

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);
        }
    }
}

这篇关于如何发生异常时跟踪所有局部变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆