Logging with HttpModule

In order to build an Http module we only need to implement 
the IHttpModule interface. The following is a simple 
LoggingHttpModule which log details when a web request start 
and when web request end: 
using System;
using System.Web;
using Microsoft.Practices.EnterpriseLibrary.Common.Configuration;
using Microsoft.Practices.EnterpriseLibrary.Logging; 
namespace HttpModules
  public class LoggingHttpModule : IHttpModule
    #region Members 
    private LogWriter _writer; 
    #region IHttpModule Members 
    public void Dispose()
      if (_writer != null)
    public void Init(HttpApplication context)
      context.BeginRequest += new EventHandler(context_BeginRequest);
      context.EndRequest += new EventHandler(context_EndRequest);
    private void CreateLogWriter()
      _writer = EnterpriseLibraryContainer.Current.GetInstance<LogWriter>();
    private void ConfigureEnterpriseLibraryContainer()
      var builder = new ConfigurationSourceBuilder(); 
               .FlatFile("Log File")
               .FormatWith(new FormatterBuilder()
      var configSource = new DictionaryConfigurationSource();
      EnterpriseLibraryContainer.Current =
    void context_BeginRequest(object sender, EventArgs e)
      _writer.Write(new LogEntry
        Message = "BeginRequest"
    void context_EndRequest(object sender, EventArgs e)
      _writer.Write(new LogEntry
        Message = "EndRequest"


In order to use the module all we need to do is to add a reference
to the class library that holds the LoggingHttpModule. Then we need
to register the module in the web.config file in the httpModules 
element like:

    <add name="LoggingHttpModlue" type="HttpModules.LoggingHttpModule, HttpModules"/>

That is it. Now the module will be executed whenever a request
start or end.

Leave a comment

Filed under .Net

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 )

Google photo

You are commenting using your Google 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 )

Connecting to %s