Hooking up log4net to ASP.NET using HttpModule

Caveat: This post is more for future self-reference than anything.

A client recently asked us to troubleshoot an asp.net web app that was generating a exception upon validating/submitting a particular windows certificate. The trace log seemed to point to a problem with the certificate itself, but we didn’t have access to it. Unfortunately the existing validation code didn’t have any logging in itself to get more feedback. Another challenge was that this app was mainly written in php with a small web service api written in C#. The code throwing the exception was in this api, so we decided to add some log4net logging to help us with this task. Here’s a summary of what we did:

Configuring log4net

We tried multiple configurations we found on the web (via Web.config or even Global.asax), but here’s the one that worked for us:

Using a custom HttpModule:

    
public class Log4NetModule : IHttpModule
{
    private static bool _configured = false;

    public void Init(HttpApplication context)
    {
        context.BeginRequest += new EventHandler(context_BeginRequest);
    }

    void context_BeginRequest(object sender, EventArgs e)
    {
        if (!_configured)
        {
            InitializeLog4Net();
            _configured = true;
        }
    }

    public void Dispose()
    {
        // Do nothing
    }

    private void InitializeLog4Net()
    {
        var layout = new log4net.Layout.PatternLayout(@"%d [%t]%-5p %c [%x] <%X{auth}> - %m%n");
        var logfile = Path.Combine(Path.Combine(HttpContext.Current.Request.PhysicalApplicationPath, "Logs"), "log.txt");
        var rollingFileAppender = new RollingFileAppender
        {
            Threshold = Level.All,
            AppendToFile = true,
            Layout = layout,
            File = logfile,
            MaxFileSize = 1000 * 1024
            RollingStyle = RollingFileAppender.RollingMode.Date,
            DatePattern = "Date",
            StaticLogFileName = true,
        };

        layout.ActivateOptions();
        rollingFileAppender.ActivateOptions();
        log4net.Config.BasicConfigurator.Configure(rollingFileAppender);
    }
}

Note this line of code:
HttpContext.Current.Request.PhysicalApplicationPath
// This returns the app’s current dir. Use this instead of Directory.GetCurrentDirectory()

Using this approach, this is the only change needed in Web.config:

  <system.web>
    <httpmodules>
      <add name="Log4NetModule" type="E222.OrderValidationService.Log4NetModule,E222.OrderValidationService" />
    </httpmodules>
  </system.web>

Adding the log statements

After this, the logging statements were ready to be put in place. E.g.:

var log = log4net.LogManager.GetLogger(typeof(MyClass));
log.Debug(&quot;My debug message&quot;);

Advertisement

Tags: ,


Follow

Get every new post delivered to your Inbox.