Format of Tracing output in System.Diagnostics.TraceSource

Flagg1980 picture Flagg1980 · Nov 8, 2012 · Viewed 11.8k times · Source

The following code:

static void Main(string[] args)
{
    TraceSource ts = new TraceSource("MyApplication");

    ts.Switch = new SourceSwitch("MySwitch");
    ts.Switch.Level = SourceLevels.All;

    ts.Listeners.Add(new TextWriterTraceListener(Console.Out));

    ts.TraceInformation("Hello World");
    Console.ReadKey();
}

generates the following output:

MyApplication Information: 0 : Hello World

The part "MyApplication Information: 0 :" at the beginning of the trace output is coming from the TraceSource class itself.

However, I need to have a timestamp at the beginning of the line and I would like to change "Information" to "Info" also.

Is there any way to get more freedom in trace output such that I can configure it to be like:

13:03:00 - MyApplication Info: Hello World

I tried for a couple of hours, but with no success. Whatever I do, at the beginning of the output line, there is always this constant predefined "MyApplication Information: 0 : Hello World" output.

MSDN documentation did also not reveal any helpful information.

Answer

ShaneB picture ShaneB · May 16, 2014

Coming in late also but in case someone else lands here...

I like keeping it simple. I use one static Trace method within my App.cs which ties to a single TraceSource that I create at start up. This allows me access it throughout my app and keep the app.config simple:

public static void Trace(TraceEventType eventType, string message)
{
    if (_TraceSource.Switch.ShouldTrace(eventType))
    {
        string tracemessage = string.Format("{0}\t[{1}]\t{2}", DateTime.Now.ToString("MM/dd/yy HH:mm:ss"), eventType, message);
        foreach (TraceListener listener in _TraceSource.Listeners)
        {
            listener.WriteLine(tracemessage);
            listener.Flush();
        }
    }
}

My app.config entries:

  <system.diagnostics>
    <sources>
      <source name="mytracesource" switchValue="All">
        <listeners>
          <add name="mytracelistener"
               type="System.Diagnostics.TextWriterTraceListener"
               initializeData="trace.log">
          </add>
        </listeners>
      </source>
    </sources>
  </system.diagnostics>