I need to implement raw xml logging before the our wcf service process the incoming request from the clinet how to implement it give the approach

Dinesh Sadhasivam 45 Reputation points
2026-06-23T06:12:10.5466667+00:00

I need to log my incoming SOAP request as raw xxml in my app before it even comes into my WCF pipeline. How to implement it? Provide me with the idea and implementations, and it will help. Thanks in advance

#WCF

Developer technologies | .NET | Other

Answer accepted by question author

Danny Nguyen (WICLOUD CORPORATION) 7,345 Reputation points Microsoft External Staff Moderator
2026-06-23T08:52:13.14+00:00

Hi @Dinesh Sadhasivam

If you only need the raw SOAP XML for troubleshooting, the simplest approach is to enable WCF message logging in web.config / app.config. WCF can log messages at the transport and service level before they reach your service operation code. Microsoft documents this under WCF message logging configuration. [learn.microsoft.com]

Example:

<system.diagnostics>
  <sources>
    <source name="System.ServiceModel.MessageLogging">
      <listeners>
        <add name="messages"
             type="System.Diagnostics.XmlWriterTraceListener"
             initializeData="C:\Logs\messages.svclog" />
      </listeners>
    </source>
  </sources>
</system.diagnostics>

<system.serviceModel>
  <diagnostics>
    <messageLogging
      logEntireMessage="true"
      logMessagesAtServiceLevel="true"
      logMessagesAtTransportLevel="true"
      logMalformedMessages="true"
      maxMessagesToLog="3000"
      maxSizeOfMessageToLog="2000000" />
  </diagnostics>
</system.serviceModel>

Make sure the C:\Logs folder exists and the application pool / service account has permission to write there.

If you need to log the SOAP XML inside your application code before the service method is called, use IDispatchMessageInspector. Its AfterReceiveRequest method is called after WCF receives the request but before it dispatches the message to the service operation. Microsoft also documents this approach here: How to inspect and modify messages on the service. [learn.microsoft.com]

Example:

using System;
using System.IO;
using System.ServiceModel;
using System.ServiceModel.Channels;
using System.ServiceModel.Dispatcher;
using System.Xml;

public class RawSoapMessageInspector : IDispatchMessageInspector
{
    public object AfterReceiveRequest(ref Message request, IClientChannel channel, InstanceContext instanceContext)
    {
        // WCF Message can only be read once, so create a buffered copy
        MessageBuffer buffer = request.CreateBufferedCopy(int.MaxValue);

        // Copy for logging
        Message copy = buffer.CreateMessage();

        using (StringWriter sw = new StringWriter())
        using (XmlWriter xw = XmlWriter.Create(sw))
        {
            copy.WriteMessage(xw);
            xw.Flush();

            string rawSoapXml = sw.ToString();

            File.AppendAllText(
                @"C:\Logs\IncomingSoap.log",
                rawSoapXml + Environment.NewLine);
        }

        // Recreate the request so WCF can continue processing it
        request = buffer.CreateMessage();

        return null;
    }

    public void BeforeSendReply(ref Message reply, object correlationState)
    {
        // Optional: log response here
    }
}

Then attach it using a service behavior:

using System.Collections.ObjectModel;
using System.ServiceModel;
using System.ServiceModel.Channels;
using System.ServiceModel.Description;
using System.ServiceModel.Dispatcher;

public class RawSoapLoggingBehavior : Attribute, IServiceBehavior
{
    public void ApplyDispatchBehavior(ServiceDescription serviceDescription, ServiceHostBase serviceHostBase)
    {
        foreach (ChannelDispatcher channelDispatcher in serviceHostBase.ChannelDispatchers)
        {
            foreach (EndpointDispatcher endpointDispatcher in channelDispatcher.Endpoints)
            {
                endpointDispatcher.DispatchRuntime.MessageInspectors.Add(new RawSoapMessageInspector());
            }
        }
    }

    public void AddBindingParameters(
        ServiceDescription serviceDescription,
        ServiceHostBase serviceHostBase,
        Collection<ServiceEndpoint> endpoints,
        BindingParameterCollection bindingParameters)
    {
    }

    public void Validate(ServiceDescription serviceDescription, ServiceHostBase serviceHostBase)
    {
    }
}

Apply it to your service class:

[RawSoapLoggingBehavior]
public class MyService : IMyService
{
    public string MyOperation()
    {
        return "OK";
    }
}

The key point is that you should not directly read the original Message and then continue processing it, because the WCF message body is forward-only. Create a buffered copy, log one copy, and assign another copy back to request.

Also, be careful when logging full SOAP messages in production, because the XML may contain passwords, tokens, personal data, or other sensitive values. If you found my response helpful or informative, I would greatly appreciate it if you could follow this guidance or provide feedback.

Thank you. 

Was this answer helpful?

1 person found this answer helpful.

Answer accepted by question author

Senthil kumar 1,120 Reputation points
2026-06-23T07:54:12.2066667+00:00

Was this answer helpful?

1 person found this answer helpful.

1 additional answer

Sort by: Most helpful
  1. AI answer

    2026-06-23T06:12:27.55+00:00

    WCF already provides built‑in raw XML logging of incoming and outgoing messages via message logging and tracing, without custom code before the service code runs.

    To log the raw SOAP request before it reaches service implementation code, enable message logging at the transport and/or service level in configuration. Logging at these levels happens before the message is dispatched to user code.

    Basic approach:

    1. Enable WCF message logging in system.serviceModel.
    2. Configure what to log (transport/service/malformed, headers vs full body, size limits).
    3. Configure a System.Diagnostics trace listener to write the logs to a file.
    4. Ensure the log directory exists and has appropriate permissions.

    Key configuration elements

    1. Message logging levels and options (in system.serviceModel):
      • logMessagesAtTransportLevel="true" logs messages as they are encoded/decoded for the wire.
      • logMessagesAtServiceLevel="true" logs messages just before they enter user code and just after they leave it.
      • logMalformedMessages="true" logs messages rejected by the WCF stack.
      • logEntireMessage="true" logs both headers and body; false logs only headers.
      • maxSizeOfMessageToLog controls how much of the message is logged (default 256 KB).
      From the logging behavior:
      • Incoming messages are logged "immediately after the message is formed, immediately before the message gets to user code in the service level, and when malformed messages are detected."
      • Outgoing messages are logged "immediately after the message leaves user code and immediately before the message goes on the wire."
    2. Trace listener configuration (in system.diagnostics):
      • Configure a listener (for example, XmlWriterTraceListener) to write logs to a .svclog file.
      • Ensure the target directory (for example, C:\logs\) exists; trace files are not created if the directory is missing.

    High‑level implementation steps

    1. In the service’s config file (Web.config or App.config), under <system.serviceModel>, configure message logging similar to:
         <system.serviceModel>
           <diagnostics>
             <messageLogging 
               logMessagesAtServiceLevel="true"
               logMessagesAtTransportLevel="true"
               logMalformedMessages="true"
               logEntireMessage="true"
               maxSizeOfMessageToLog="262144" />
           </diagnostics>
         </system.serviceModel>
      
    2. Under <system.diagnostics>, configure the trace listener that will receive the logged messages and write them to disk. The sample guidance notes:
      • "Messages are logged in XML format in the target directory specified in the configuration file."
      • "Trace files are not created without initially creating the log directory. Make sure that the directory C:\logs\ exists, or specify an alternate logging directory in the listener configuration."
    3. Create the log directory (for example, C:\logs\) and grant write access to the identity hosting the service (for example, Network Service when using WAS/IIS), as described in the tracing and message logging sample setup.
    4. Run the service. Incoming SOAP messages will be logged as XML before they reach the service implementation. Use tools such as SvcTraceViewer.exe (not detailed in the provided context but standard for WCF) to inspect .svclog files.

    Notes on what is logged

    • At the service level, secure messages are logged decrypted, and infrastructure messages (transactions, peer channel, security) are logged (except Reliable Messaging messages).
    • At the transport level, messages are logged as they are on the wire (typically encrypted if message security is used, except when using HTTPS where they are logged decrypted before send/after receive).
    • Malformed messages are logged as‑is, including invalid XML or encrypted content.

    This configuration‑based approach satisfies the requirement to capture the raw SOAP XML before the WCF service code processes the request, without needing a custom HTTP module or custom channel.


    References:

    AI-generated content may be incorrect. Read our transparency notes for more information.

    Was this answer helpful?

Your answer

Answers can be marked as 'Accepted' by the question author and 'Recommended' by moderators, which helps users know the answer solved the author's problem.