Skip to content

Instantly share code, notes, and snippets.

@WizzApp
Created May 22, 2013 13:18
Show Gist options
  • Save WizzApp/5627481 to your computer and use it in GitHub Desktop.
Save WizzApp/5627481 to your computer and use it in GitHub Desktop.
How to log the raw xml messages in WCF
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.ServiceModel.Configuration;
using System.ServiceModel.Description;
using System.ServiceModel.Dispatcher;
using System.Text;
using log4net;
namespace TechProtect.Backbone.Service
{
public class WcfMessageLogger: IDispatchMessageInspector, IServiceBehavior
{
ILog log;
public WcfMessageLogger(ILog log)
{
this.log = log;
}
public object AfterReceiveRequest(ref System.ServiceModel.Channels.Message request, System.ServiceModel.IClientChannel channel, System.ServiceModel.InstanceContext instanceContext)
{
log.Debug(request.ToString());
return null;
}
public void BeforeSendReply(ref System.ServiceModel.Channels.Message reply, object correlationState)
{
log.Debug(reply.ToString());
}
public void AddBindingParameters(ServiceDescription serviceDescription, System.ServiceModel.ServiceHostBase serviceHostBase, System.Collections.ObjectModel.Collection<ServiceEndpoint> endpoints, System.ServiceModel.Channels.BindingParameterCollection bindingParameters)
{
}
public void ApplyDispatchBehavior(ServiceDescription serviceDescription, System.ServiceModel.ServiceHostBase serviceHostBase)
{
log4net.Config.XmlConfigurator.Configure();
ILog log = LogManager.GetLogger(typeof(IMainService));
foreach (ChannelDispatcher dispatcher in serviceHostBase.ChannelDispatchers)
{
foreach (var endpoint in dispatcher.Endpoints)
{
endpoint.DispatchRuntime.MessageInspectors.Add(new WcfMessageLogger(log));
}
}
}
public void Validate(ServiceDescription serviceDescription, System.ServiceModel.ServiceHostBase serviceHostBase)
{
}
}
public class WcfMessageLoggerExtension : BehaviorExtensionElement
{
protected override object CreateBehavior()
{
log4net.Config.XmlConfigurator.Configure();
ILog log = LogManager.GetLogger(typeof(IMainService));
return new WcfMessageLogger(log);
}
public override Type BehaviorType
{
get { return typeof(WcfMessageLogger); }
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment