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

/**//// <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(0, 250, 0);
break;
case 1:
color = Color.FromArgb(50, 200, 0);
break;
case 2:
color = Color.FromArgb(100, 150, 0);
break;
case 3:
color = Color.FromArgb(150, 100, 0);
break;
case 4:
color = Color.FromArgb(200, 50, 0);
break;
default:
color = Color.FromArgb(250, 0, 0);
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
using System;
using System.Collections.Generic;
using System.Text;
using System.Diagnostics;
using System.Windows.Forms;
using System.Drawing;

namespace RPTestApp


{
class MyTraceListener : TraceListener

{
private RichTextBox _richTextBox = null;

public MyTraceListener(RichTextBox richTextBox)

{
this._richTextBox = richTextBox;
}

private delegate void WriteDelegate(string message);
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(0, 250, 0);
break;
case 1:
color = Color.FromArgb(50, 200, 0);
break;
case 2:
color = Color.FromArgb(100, 150, 0);
break;
case 3:
color = Color.FromArgb(150, 100, 0);
break;
case 4:
color = Color.FromArgb(200, 50, 0);
break;
default:
color = Color.FromArgb(250, 0, 0);
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();
}

public override void Write(string message)

{
//This is for thread safety

this._richTextBox.Invoke(new WriteDelegate(this.WriteImpl), new object[]
{ message });
}

public override void WriteLine(string message)

{
this.Write(message + Environment.NewLine);
}

}
}