Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to enable IP address logging with Log4Net

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

like image 954
Tadas Šukys Avatar asked Aug 27 '09 12:08

Tadas Šukys


People also ask

How do I use log4net net 6?

Just create a log4net. config file with a log file as an appender, then add two using statements and a single line of code to the new . NET 6 hosting model: //Program.

Does log4net support .NET core?

Recently the log4net team published new NuGet packages that support . NETStandard 1.3, which means it should work with . NET Core.

Why should I use log4net?

log4net is a tool to help the programmer output log statements to a variety of output targets. In case of problems with an application, it is helpful to enable logging so that the problem can be located. With log4net it is possible to enable logging at runtime without modifying the application binary.


2 Answers

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).

like image 178
Jacob Avatar answered Sep 28 '22 12:09

Jacob


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.

like image 24
Vinay Sajip Avatar answered Sep 28 '22 11:09

Vinay Sajip