15

I'm looking a way to enable IP logging with log4net in ASP.NET. I found one solution but it works at Application level. Any suggestions/practices how to log IP at session level?

Thanks

Tadas Šukys
  • 4,140
  • 4
  • 27
  • 32

2 Answers2

20

With log4net 1.2.11 (Oct 2011) you add the following to your pattern layout:

%aspnet-request{REMOTE_ADDR}

Or for the current user:

%aspnet-request{AUTH_USER}

See https://issues.apache.org/jira/browse/LOG4NET-87 for more info on the new asp.net patterns converters (%aspnet-cache, %aspnet-context, and %aspnet-request).

Jacob
  • 7,741
  • 4
  • 30
  • 24
  • Looking at the jira comments, it looks like it lacks support of buffered appenders such as AdoNetAppender, when buffer size is greater than 1. Have you used them with such appenders? – Frédéric Aug 31 '15 at 10:19
19

In Application_BeginRequest, do

MDC.Set("addr", Request.UserHostAddress);

and then ensure that your PatternLayout contains %X{addr} somewhere in the pattern string.

Update: As Tadas has pointed out, in newer versions of log4net the equivalent is

ThreadContext.Properties["addr"] = Request.UserHostAddress;

coupled with %P{addr} in the pattern string.

Vinay Sajip
  • 95,872
  • 14
  • 179
  • 191
  • 1
    Great! Thanks. I just want to note that MDC class is deprecated (http://svn.apache.org/repos/asf/logging/site/trunk/docs/log4net/release/sdk/log4net.MDC.html) and forwards to ThreadContext.Properties. – Tadas Šukys Aug 27 '09 at 12:32
  • Nice - I had done this in a previous life, but had forgotten how. +1 – Jarrod Dixon Oct 07 '09 at 09:12
  • Beware of asp.net 'thread agility' feature : it defeats log4net contexts. See [this blog](http://piers7.blogspot.com/2005/12/log4net-context-problems-with-aspnet.html) and [this answer](http://stackoverflow.com/a/9000825/1178314) on another question for more details. – Frédéric Aug 31 '15 at 10:16