How to Add a Trace Listener to Log Messages in a WCF Service?

To enable your WCF service or WCF client application to log messages, you must add the necessary configuration elements to the WCF configuration of your application. The following WCF configuration example shows how you can configure message logging in its simplest form

Step 1

Add a source element for the System.ServiceModel.MessageLogging trace source.

  <system.diagnostics>

    <sources>

      <source name="System.ServiceModel.MessageLogging">

      </source>

    </sources>

  </system.diagnostics>

 

 

Step 2

Add a trace listener for the message-logging trace source. This can be one of several different types of trace listener:EventLogTraceListener, TextWriterTraceListener, or XmlWriterTraceListener.

  <source name="System.ServiceModel.MessageLogging">

    <listeners>

      <add name="messages"

          type="System.Diagnostics.XmlWriterTraceListener"

    </listeners>

  </source>

 

Step 3

Set the location where you want the trace listener to record the messages. Typically, you do this by setting the initializeData property.

  <source name="System.ServiceModel.MessageLogging">

    <listeners>

      <add name="messages"

          type="System.Diagnostics.XmlWriterTraceListener"

          initializeData="c:\\logs\\messages.svclog" />

    </listeners>

  </source>

 

Step 4

Set the autoflush property to true. This tells the trace listener to push the messages to the log after every write operation rather than buffering them in memory.

         </listeners>

      </source>

   </sources>

   <trace autoflush="true" />

</system.diagnostics>

You can enable message logging either programmatically in a class file or declaratively in an application configuration file. If you choose to use the declarative approach, you can add your message-logging configuration to the Diagnostics folder by using the WCF Configuration Editor. The WCF Configuration Editor does not require you to write raw XML.

For more information, see Configuring Message Logging.