C# MVC log all incoming request (SOAP and REST)

Posted: 2014-05-18 in .Net

I recently worked on a high profile site. One requirement was clear any failed issues leads us to legally liable. In many cases for large sums of money.

So to cover our butts we logged the entire incoming and outgoing SOAP messages.

Storage is cheap, law suits are not and an additional 0.050ms is easy to justify, especially as this enabled us code replay for problematic request.

So lets get started:

First you need the code.

https://gist.github.com/ChocoSmith/0055a8ed92e57cf0e6a3

using System;
using System.Text;
using System.Web;
using NLog;

namespace Choco.Shared.Web.App_Start
{
	public class LogSoapModule : IHttpModule
	{
		public void Init(HttpApplication context)
		{
			context.BeginRequest += this.OnBegin;
		}

		private void OnBegin(object sender, EventArgs e)
		{
			var context = ((HttpApplication) sender).Context;

			var innerLogger = LogManager.GetLogger("incomingRequest");
			innerLogger.Info(context.Request.Url);

			if (!innerLogger.IsTraceEnabled)
				return;

			byte[] buffer = new byte[context.Request.InputStream.Length];
			context.Request.InputStream.Read(buffer, 0, buffer.Length);
			context.Request.InputStream.Position = 0;

			string soapMessage = Encoding.ASCII.GetString(buffer);

			if (!string.IsNullOrEmpty(soapMessage))
				innerLogger.Trace(soapMessage);
		}

		public void Dispose()
		{
			//
		}
	}
}

The code is triggered by enabling it. Since this is a IHttpModule we can simply do this via the web.config.

<system.webServer>
	<modules runAllManagedModulesForAllRequests="true">
		<add name="LogSoapModule" type="Choco.Shared.Web.App_Start.LogSoapModule" />
	</modules>
</system.webServer>

This has the advantage that you can simply activate or deactivate if you don’t need it runing all the time.

One more thing:

Because I was using NLOG, I added a configuration section for “incomingRequest” to the nlog configuration file. I seperated out these logs into a separate file and large cheap storage.

Happy logging

Cheers,
Choco

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s