REQUEST A DEMO

Getting a ASP.Net request URL into a log4net context

We make a lot of web applications and we use a lot of logging to diagnose problems on production systems. Often I find myself wishing I knew what URL was being rendered for a given log. In this post I’ll take you through a good solution for adding the current request URL to the log4net context. Better yet we will do this a configurable way so that you can turn this on and off when needed.

One perfectly good way to do this would be to add a debug log to the start of each web request.  What I don’t like about this is that it can be tricky to scan logs with simultaneous requests and thus URLs being handled and keep track of which thread is being used to render what URL. Log4net has a context mechanism where you “push” context into “stacks”.

The push method returns a log context which implements IDisposible. When the context is disposed the context is popped off the stack. This allows you to push many different contexts onto the stack.

Let’s take a look at a simple HttpModule which you can use to push the current request’s url into the log context

This module registers two event handlers on begin and end request where begin gets a logger from an IoC container pushes the request url into the context. When the request completes (or the module is disposed) the context is cleaned up effectively removing the url off the log context stack.

A nice side-effect of making this a HTTPModule is that you can add or remove this HttpModule to your application as needed using IIS Manager or by editting your web.config.

And make sure you configure log4net appenders to include the context in log output pattern.

Finally here is an example of this module in action with the configuration settings you are seeing above.

I hope you find this handy. If so let me know. Not so much? Go watch kitten videos on youtube