C# Add a footer to a trace listener when closed

333 views Asked by At

How can one add a footer to a trace listener which is defined in the app.config:

<system.diagnostics>
<switches>
  <!-- Set loglevel for diagnostic messages
  (0=none, 1=errors, 2=warnings, 3=info, 4=verbose) -->
  <add name="logLevel" value="4" />
</switches>
<trace autoflush="true" indentsize="4">
  <listeners>
    <add name="FileListener"
         type="System.Diagnostics.TextWriterTraceListener"
         initializeData="Logs\QFXLog.txt" />
    <remove name="Default" />
  </listeners>
</trace>

I want to write an end footer when this listener is closed. What entries are to be defined in the config(if any?) and where must one define the footer string in code?

Thanks, Juergen

1

There are 1 answers

0
Fueled On BEST ANSWER

I don't know of any way to handle this directly in the app.config file, but you could implement a class which inherits TextWriterTraceListener and then override its Close method:

namespace MyNamespace
{
    public class FormattedTextTracer : TextWriterTraceListener
    {
        public override void Close()
        {
             // Write footer
             Writer.WriteLine("==== Footer ====");
             Writer.Flush();
             base.Close();
        }
    }
}

And in the app.config file, replace the listener type with your class:

<listeners>
    <add name="FileListener"
     type="MyNamespace.FormattedTextTracer, MyNamespace"
     initializeData="Logs\QFXLog.txt" />
    <remove name="Default" />
</listeners>