5

As far as I can see, there are two ways to create trace messages in .NET.

  1. The static methods of System.Diagnostics.Trace:

    Trace.WriteLine("Something happened");
    
  2. The instance methods of System.Diagnostics.TraceSource:

    var ts = new TraceSource("TraceTest");
    ts.TraceInformation("Something happened");
    

In my app.config file, I can either add a trace listener for everything:

<system.diagnostics>
    <trace>
        <listeners>
            ...
        </listeners>
    </trace>
</system.diagnostics>

or for one particular trace source:

<system.diagnostics>
    <sources>
        <source name="...">
            <listeners>
                ...
            </listeners>
        </source>
    </sources>
</system.diagnostics>

My question

If I use the first method (static methods of System.Diagnostics.Trace), which trace source name is used?

I've checked the MSDN page of System.Diagnostics.Trace, but did not find the answer there.

Heinzi
  • 167,459
  • 57
  • 363
  • 519
  • I don't think it uses a Source. It acts like a kind of 'global source' . Two parallel APIs, probably a historical relic. – H H Dec 28 '15 at 10:11
  • @HenkHolterman: That's quite possible (trace sources were added in v2.0), but I haven't found proof for it yet. However, it's also conceivable that they added a specific source for those "legacy" operations. – Heinzi Dec 28 '15 at 10:26

1 Answers1

3

I checked the source of Trace.Writeline with JustDecompile and it enums all listeners and sends the message to all:

                foreach (TraceListener listener in TraceInternal.Listeners)
                {
                    if (listener.IsThreadSafe)
                    {
                        listener.WriteLine(message);
                        if (!TraceInternal.AutoFlush)
                        {
                            continue;
                        }
                        listener.Flush();
                    }
                    else
                    {
                        lock (listener)
                        {
                            listener.WriteLine(message);
                            if (TraceInternal.AutoFlush)
                            {
                                listener.Flush();
                            }
                        }
                    }
                }

But forget this ugly Trace calls, use ETW Eventsource for a much better tracing/logging

magicandre1981
  • 27,895
  • 5
  • 86
  • 127