October 19, 2017

WCF Service - How to log custom messages using Trace.Write()

In this post I will explain how to write custom logging messages in WCF tracing. I found many articles showing how to enable tracing and can see the default messages when service gets invoked. A good post from MSDN I found is:

https://docs.microsoft.com/en-us/dotnet/framework/wcf/samples/tracing-and-message-logging

It works well and get enabled to view default messages for different WCF methods. But I was facing problem when tried to write custom messages within WCF service.

After searching I found following trick to work for me. This will allow you to write custom messages from coding.

This is how your write log message from C# code using Trace class.

Trace.WriteLine("Custom message goes here...")
// We need to call Flush() method to empty the output buffer for tracing.
Trace.Flush();

Next step is to add a listener in the Listeners Collection to get the receive messages from trace output methods, you can do this adding following lines in your app.config or web.config file.

<configuration>
  <system.diagnostics>
    <trace autoflush="false" indentsize="4">
      <listeners>
        <add name="myListener" type="System.Diagnostics.TextWriterTraceListener" initializeData="C:\Test\WcfTracingExample.log" />
        <remove name="Default" />
      </listeners>
    </trace>
  </system.diagnostics>
</configuration>

I used the path C:\Test\WcfTracingExample.log for log file, you may want to change according to your environment, just make sure that you have write permissions enabled for this directory and file.

You can also use other methods from Trace class apart from Write():

System.Diagnostics.Trace.TraceError("TraceError: GetData");
System.Diagnostics.Trace.TraceInformation("TraceInformation: GetData");
System.Diagnostics.Trace.TraceWarning("TraceWarning: GetData");
System.Diagnostics.Trace.WriteLine("WriteLine: GetData");
// Then call the Flush() method to empty the buffer.
System.Diagnostics.Trace.Flush();

No comments:

Post a Comment