Search code examples
.nettracesystem.diagnostics

Does System.Diagnostics.Trace do nothing is there are no listeners?


I'd like to be able to leave Trace in the live assembly, but only if the trace is NoOp. This is for the same reason I don't want to spam the the Event Log.

So, if I output detailed operational information to the Trace methods, will they only actually be stored\collected if I have a trace listener attached?

i.e. They won't be written to the hard drive or stored somewhere?


Solution

  • MSDN: Trace Listeners:

    When using Trace, Debug and TraceSource, you must have a mechanism for collecting and recording the messages that are sent. Trace messages are received by listeners. The purpose of a listener is to collect, store, and route tracing messages. Listeners direct the tracing output to an appropriate target, such as a log, window, or text file.

    So when you have no listeners, the output will not be stored somewhere.

    You can do this (which is the recommended way to configure tracing anyway) in configuration:

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

    Or from code:

    System.Diagnostics.Trace.Listeners.Clear();