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
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.
Recently the log4net team published new NuGet packages that support . NETStandard 1.3, which means it should work with . NET Core.
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.
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).
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With