May
7
2013
C# // Tracing // WCF

C#.Net – WCF – How To: Enable WCF Tracing and MessageLogging

In previous C# tutorial we learned how to enable tracing in asp.net. Now, in this wpf tutorial we are going to see how to enable wcf tracing.

Here i am assuming that you know how to create, host and consume WCF services If you don’t know or having a little knowledge then i would suggest you to refer WCF tutorials page that includes all WCF related articles.

Before we start, lets learn what is wcf tracing and why we need tracing in wcf?

What is WCF Tracing?

WCF Tracing and MessageLogging
WCF Tracing and MessageLogging

The meaning and definition of WCF tracing is not different than the traditional tracing we use in Asp.net. WCF trace mechanism gives us a power to log and save the diagnostic data in a persisted manner. In short – application provides information about itself thru this diagnostic data. Once the traced data is available we can use it for fault analysis and monitoring.

WCF tracing is derived from System.Diagnostics namespace which is used for debugging and tracing only. This wcf trace log data can track all events thru different tracing levels.

WCF tracing provides us different wcf tracing levels as given below –

Sr. No
Trace Level
Event Category
Tracing Details
Traced Events
1
Off
– (No Tracing)
Ignores tracing.
2
Critical
Negative Events
Unexpected events or any error condition. When occurs, application may shut shortly or immediately.
1)      All unexpected events
2)      OutOfMemoryException
3)      ThreadAbortException
4)      StackOverFlowException
5)      ConfigurationErrorsException
6)      SEHException
7)      Application start errors
8)      System Hang errors
9)      All other traces that cause application to terminate
3
Error
Negative Events
Unexpected events or any error condition. When occurs, application does not shut, it remains up & continues processing.
Traces all exceptions.
4
Warning
Negative Events
Indicates possibility of problems. Application remains up and continues the processing.
Traces all possible problems that are occurred or may occur.
1)   TimeOut has exceeded
2)   Rejected credentials
3)   Receiving more request than expected.
4)   Receiving Queue is nearby maximum capacity.
5
Information
Positive Events
Only informative traces that tells the successful milestone of application execution.
Traces all diagnostic data.
6
Verbose
Positive Events
Same as “Information”, however only difference is – it allows low level tracing.
Mostly used for Debugging purpose.
7
ActivityTracing
The traces are related to communication between components and activities.
8.
All
Positive & Negative
It includes all above events
It includes all above events

WCF defines few trace sources that are needed to trace the wcf service. WCF has trace source for each WCF assembly. To enable the wcf trace we need to mention the trace source in configuration file like Web.config. Mostly and widely used trace source is System.ServiceModel. Another trace source which is mostly used for WCF Message logging is System.ServiceModel.MessageLogging.

To enable the tracing we also need a TraceListener. Now what is TraceListener? These are the objects that actually get tracing information from source and save the data.

How to enable WCF Tracing?

In one of previous post I have explained how to create WCF service and then consume it in WPF application. In this article I am going to take the same example to demonstrate how to enable wcf service trace.

Steps to enable WCF tracing.

By default WCF service does not trace any messages. To add wcf tracing, please follow below steps –

  1. Open your web.config file from solution explorer. The contents of newly created Service would look a like –
    <?xml version=1.0?>

    <configuration>
      <system.web>
        <compilation debug=true targetFramework=4.0 />
      </system.web>
      <system.serviceModel>
        <behaviors>
          <serviceBehaviors>
            <behavior>
              <!– To avoid disclosing metadata information, set the value below to false and remove the metadata endpoint above before deployment –>
              <serviceMetadata httpGetEnabled=true/>
              <!– To receive exception details in faults for debugging purposes, set the value below to true.  Set to false before deployment to avoid disclosing exception information –>
              <serviceDebug includeExceptionDetailInFaults=false/>
            </behavior>
          </serviceBehaviors>
        </behaviors>
        <serviceHostingEnvironment multipleSiteBindingsEnabled=true />
      </system.serviceModel>
     <system.webServer>
        <modules runAllManagedModulesForAllRequests=true/>
      </system.webServer>
    </configuration>

    In above code tracing and message logging both are not enabled.

  2. To enable the MessageLogging we need to add following code in above web.config file. The important point is MessageLogging can be done at two levels. i.e. service level and another is transport level. Please add given code after the </behaviours> tag highlighted in above code snippet.
        <diagnostics>

          <messageLogging logEntireMessage=true
                          logMessagesAtServiceLevel=false
                          logMessagesAtTransportLevel=false
                          logMalformedMessages=true
                          maxMessagesToLog=5000
                          maxSizeOfMessageToLog=2000>
          </messageLogging>
        </diagnostics>

    Here…

    Sr. No

    Attribute

    Description

    1

    logEntireMessage

    “true” value indicates that the entire message should be logged.

    2

    logMessagesAtServiceLevel

    “true” means service-level messages will be logged.

    3

    logMessagesAtTransportLevel

    Transport level messages will be logged if set to “true”.

    4

    logMalformedMessages

    Malformed message should be logged if set to “true”

    5

    maxMessagesToLog

    This is the number that tells how many messages to be logged.

    6

    maxSizeOfMessageToLog

    The value indicates the maximum size of the message log. Default is 256Kb

  3. As mentioned above, we need to define trace source and TraceListener to activate wcf tracing. In below code snippet we have added both Trace Source mentioned earlier and created an object of a tracelistener named as “TextLogger” which will act as a shared tracelistener for both trace sources.

    Copy and paste below code snippet just after </system.webServer> tag highlighted in first code snippet –

      <system.diagnostics>
        <trace autoflush=true indentsize=4 />
        <sources>
          <source name=System.ServiceModel switchValue=All>
            <listeners>
              <add name=textLogger />
            </listeners>
          </source>
          <source name=System.ServiceModel.MessageLogging switchValue=All>
            <listeners>
              <add name=textLogger />
            </listeners>
          </source>
        </sources>
        <sharedListeners>
          <add name=textLogger
               type=System.Diagnostics.TextWriterTraceListener
               initializeData=C:WCF_logswcf_svclog.txt />
        </sharedListeners>
      </system.diagnostics>

    Please note : Here we have set autoflush=true. If we don’t do that there will be a possibility that the trace file would be corrupted. It would open in any text editor, however WCF trace viewer would not be able to open such corrupted file.

  4. Just change the location of a trace output file highlighted in yellow in above code as per your convenience. Save the file and we are done with the process of enabling wcf tracing. Now execute the WCF service and check the log/trace file created at above highlighted location.
  5. Complete code of Web.config file used in above example for MessageLogging and TraceListener is available here –
<?xml version=1.0?>

<configuration>
  <system.web>
    <compilation debug=true targetFramework=4.0 />
  </system.web>
  <system.serviceModel>
    <behaviors>
      <serviceBehaviors>
        <behavior>
          <!– To avoid disclosing metadata information, set the value below to false and remove the metadata endpoint above before deployment –>
          <serviceMetadata httpGetEnabled=true/>
          <!– To receive exception details in faults for debugging purposes, set the value below to true.  Set to false before deployment to avoid disclosing exception information –>
          <serviceDebug includeExceptionDetailInFaults=false/>
        </behavior>
      </serviceBehaviors>
    </behaviors>
    <diagnostics>
      <messageLogging logEntireMessage=true
                      logMessagesAtServiceLevel=false
                      logMessagesAtTransportLevel=false
                      logMalformedMessages=true
                      maxMessagesToLog=5000
                      maxSizeOfMessageToLog=2000>
      </messageLogging>
    </diagnostics>
    <serviceHostingEnvironment multipleSiteBindingsEnabled=true />
  </system.serviceModel>
  <system.webServer>
    <modules runAllManagedModulesForAllRequests=true/>
  </system.webServer>
  <system.diagnostics>
    <trace autoflush=true indentsize=4 />
    <sources>
      <source name=System.ServiceModel switchValue=All>
        <listeners>
          <add name=textLogger />
        </listeners>
      </source>
      <source name=System.ServiceModel.MessageLogging switchValue=All>
        <listeners>
          <add name=textLogger />
        </listeners>
      </source>
    </sources>
    <sharedListeners>
      <add name=textLogger
           type=System.Diagnostics.TextWriterTraceListener
           initializeData=C:WCF_logswcf_svclog.txt />
    </sharedListeners>
  </system.diagnostics>
</configuration>

I hope you enjoyed the article. If it really helped you then could you please share the article with your friends on your favorite social media?

Following article might be of your interest –

About the Author: Ashish Ramteke

Ashish Ramteke is a Software Professional, Part time blogger and founder of C# Tutorials, a popular blog on C#.Net. Ashish is having 6 years of work experience and an engineering degree in Computer Science and Engg.

Leave a comment