HowTo - WCF Message Logging System

How to implement custom WCF Message Logging System.

Go to the WebServices project and open the Wcf\Inspectors\WcfServiceTrackingInspector.cs file.

Edit the TraceOperation method.

// WebServices | WcfServiceTrackingInspector.cs

namespace Com.Example.Labs.WebServices
{
    using System;
    using System.Collections.ObjectModel;
    using System.ServiceModel;
    using System.ServiceModel.Channels;
    using System.ServiceModel.Description;
    using System.ServiceModel.Dispatcher;

    using Com.Example.Labs.Core;

    public class WcfServiceTrackingInspector : IDispatchMessageInspector, IServiceBehavior
    {
        // ...

        public object AfterReceiveRequest(ref Message request, IClientChannel channel, InstanceContext instanceContext)
        {
            TraceOperation(ref request, channel, instanceContext);
            return null;
        }

        private static void TraceOperation(ref Message request, IClientChannel channel, InstanceContext instanceContext)
        {
            if (_configSection.IsEnabled)
            {
                if (!request.IsEmpty)
                {
                    if (_loggerService != null)
                    {
                        // Enter your custom code in this block...

                        string to = OperationContext.Current.IncomingMessageHeaders.To.ToString();
                        string action = OperationContext.Current.IncomingMessageHeaders.Action;
                        string operationName = action.Substring(action.LastIndexOf("/", StringComparison.OrdinalIgnoreCase) + 1);

                        string logLine = string.Format(
                            "Request from {0} -> {1} (operationName = {2})",
                            WcfHelper.GetClientIpAddress(), to, operationName);

                        if (_configSection.WithMessageLogging)
                        {
                            logLine = string.Concat(
                                logLine, Environment.NewLine, WcfHelper.MessageToString(ref request));
                        }

                        _loggerService.WriteLine("WcfServiceTracking", LogStatus.Info, logLine);
                    }
                }
            }
        }
    }
}