Tutorial :Indentation in a custom TraceListener


How should I implement supporting indentation in a custom TraceListener?

Trace.Indent();  // or  Trace.Unindent();  

Does not work even if there is an implementation for:

protected override void WriteIndent() { ... }  

In that custom TraceListener.

Am I missing something?


You can use a TextWriterTraceListener class. It supports indentation.


I think you have to call WriteIndent explicitly yourself (if I interpret correctly the documentation). This code works as expected:

using System;  using System.Xml.Serialization;  using System.Diagnostics;    class Program {        class TestListener : TraceListener {            protected override void WriteIndent() {              if (NeedIndent) {                  string indent = new string(' ',IndentLevel * IndentSize);                  Console.Write(indent);              }          }            public override void Write(string message) {              WriteIndent();              Console.Write(message);          }            public override void WriteLine(string message) {              WriteIndent();              Console.WriteLine(message);          }      }          public static void Main(params string[] args) {            Trace.Listeners.Add(new TestListener());          Trace.IndentSize = 2;          Trace.WriteLine("test");          Trace.IndentLevel = 4;          Trace.WriteLine("indented");      }  }  


I have figured it out as those 2 static methods of Trace change IndentLevel. So I am doing this:

...  if (entry.IndentLevel > 0)      writer.WriteLine(          new string(' ', entry.IndentLevel * IndentSize) +  ...  

Note:If u also have question or solution just comment us below or mail us on toontricks1994@gmail.com
Next Post »