I'm new to log4net, so hopefully this is a really easy question for someone?!
I've got log4net working with the RollingLogFileAppender for my web application. I'm using logging to try and find where some performance issues are coming from. In order to do this, it'd be useful to include the ASP.NET SessionID in the log output so that I can make sure I'm looking at log entries for a specific user.
Is there any way I can do this through the conversionPattern
setting for the appender? Is there a %property{??}
setting I can use?
UPDATE: This question still hasn't been answered - does anybody have any ideas?
UPDATE (2014-06-12): Starting from log4net 1.2.11 you can use
%aspnet-request{ASP.NET_SessionId}
in conversion pattern for this purpose.References: https://issues.apache.org/jira/browse/LOG4NET-87 http://logging.apache.org/log4net/release/sdk/log4net.Layout.PatternLayout.html
You should create Application_PostAcquireRequestState handler in Global.asax.cs (it is called in every request):
And add [%property{SessionID}] to conversionPattern.
You can try:
...in your Web.config, and in Global.asax.cs:
Alexander K. is nearly correct. The only problem with it is that the
PostAcquireRequestState
event also occurs for static requests. A call to Session in this situation will cause aHttpException
.Therefore the correct solution becomes:
Someone corrects me if I am wrong, but one ASP.NET thread can handle multiple sessions, so you can not use Session_Start as it is called once when the session starts. What it means is that as soon as a different user accesss the web site, your log4net.ThreadContext might be overwritten by the new user information.
You can either put the below code in Application_AcquireRequestState, or create a HttpModule and do that in AcquireRequestState method. AcquireRequestState is called when ASP.NET runtime is ready to acquire the Session state of the current HTTP request. If you interested in getting username, you can do that in AuthenticateRequest which is raised when ASP.NET runtime is ready to authenticate the identity of the user (and before the AcquireRequestState).
After that you can set up your log4net.config (or in web.config) like this.
Hope this helps!
I was looking answer for this too and found out that
%aspnet-request{ASP.NET_SessionId}
works fine for me.