.NET Tracing: What is the “Default” listener?

2020-03-01 03:16发布

问题:

Every example of tracing in .NET people remove the "Default" listener:

<configuration>
  <system.diagnostics>
    <sources>
      <source name="TraceSourceApp" switchName="SourceSwitch" switchType="System.Diagnostics.SourceSwitch">
        <listeners>
          <add name="ConsoleListener"/>
          <add name="ETWListener"/>
          <remove name="Default"/>
        </listeners>

What is the Default listener, and why is it there by default?

A Microsoft guy did benchmarks of the overhead with different listeners:

Default                    |===============================14,196 ms=====/ /================> 
TextWriterTraceListener    |=========211 ms======>
EventProviderTraceListener |=> 77ms

What is the Default trace listener, and why is it so slow? Is it OutputDebugString? Is OutputDebugString really two orders of magnitude slower than writing to a file?

Is there a .NET TraceListener that just uses OutputDebugString?

What is the default trace listener, why is it so slow, why is it customarily removed, and if it's so bad why is it the default?

回答1:

It's not clear from that blog post how the code was run, but the DefaultTraceListener is documented like this:

By default, the Write and WriteLine methods emit the message to the Win32 OutputDebugString function and to the Debugger.Log method. For information about the OutputDebugString function, see the Platform SDK or MSDN.

So if Debugger.Log is actually printing to a UI window (and quite possibly scrolling it etc) I can see that causing a lot of the slowdown.



回答2:

The way Trace Listeners work seems to be a little Automagical because the documentation is not very clear about it. Lets say we have a Business Case for developing a Windows Service. In that service we use Trace.Writeline statements to send information to console or file. The Default Trace Listener sends information to console. If you run the Windows Service and connect with a Debugger to a running process you can see those messages on your console. If you want to change that and send Trace information to a file you can change that in the app.config file like this :

<system.diagnostics>
    <trace autoflush="false" indentsize="4">
        <listeners>
           <remove name="Default" />
           <add name="Default" type="System.Diagnostics.TextWriterTraceListener" initializeData="ImportServiceOutput.log" />      
        </listeners>
     </trace>
</system.diagnostics>

Look at the name="Default" that could be any name "myListener" is as good as well. Because the "Default" listener was removed that one will be used instead. Microsoft should document this because this is not clear. In the Microsoft documentation it states that you should use the variable "myListener" then but thats not needed and NOT right anyway because you want declarative where Tracing should go.



标签: .net trace etw