.NET下一种简单的调试诊断方法(2)

根据上篇中介绍的策略,每一个调用栈在进入和离开时都要进行类似下面的处理:

/// <summary>
        
/// Gets the name.
        
/// </summary>
        
/// <returns></returns>

        public string getName()
        
{
            
string ret = "";

            MethodInfo method 
= (MethodInfo)MethodInfo.GetCurrentMethod();
            Debug.WriteLine(
string.Format("Enter {0}.{1}", method.DeclaringType.FullName, method.Name));
            Debug.Indent();
            
{
                
this._cmdrp.Item = new noParamType();
                
this.internalExecute();
                ret
=((stringReturnType)this._replyrp.Item).returnValue;
            }

            Debug.Unindent();
            Debug.WriteLine(
string.Format("Leave {0}.{1}", method.DeclaringType.FullName, method.Name));

            
return ret;
        }

由此带来的问题是:当调用层次太深的时候,输出的调试信息量太多了,虽然层次分明的缩进可以帮我们理清思路,但是在纷繁众多的信息中想要找到我们所需的谈何容易啊,如下所示:


因此考虑根据缩进层次着色,幸好我采用的是RichTextBox,太容易了,修改上篇中的继承类中的函数如下:
private void WriteImpl(string message)
        
{
            
if (this.NeedIndent)
            
{
                
this.WriteIndent();
                
this.NeedIndent = true;
            }

            Color color 
= new Color();
            
switch (this.IndentLevel)
            
{
                
case 0:
                    color 
= Color.FromArgb(02500);
                    
break;
                
case 1:
                    color 
= Color.FromArgb(502000);
                    
break;
                
case 2:
                    color 
= Color.FromArgb(1001500);
                    
break;
                
case 3:
                    color 
= Color.FromArgb(1501000);
                    
break;
                
case 4:
                    color 
= Color.FromArgb(200500);
                    
break;
                
default:
                    color 
= Color.FromArgb(25000);
                    
break;
            }

            
this._richTextBox.Select(this._richTextBox.Text.Length, 0);
            
this._richTextBox.SelectionBackColor = color;
            
this._richTextBox.AppendText(message);
            
this._richTextBox.Select(this._richTextBox.Text.Length, 0);
            
this._richTextBox.ScrollToCaret();
        }

具体的颜色值可以根据自己的爱好进行调整,最终的调试输出如下:


瞧,是不是很有层次感啊! 完整源码如下:
MyTraceListener
原文地址:https://www.cnblogs.com/swnuwangyun/p/688550.html