How can I include SessionID in log files using log4net in ASP.NET? How can I include SessionID in log files using log4net in ASP.NET? asp.net asp.net

How can I include SessionID in log files using log4net in ASP.NET?


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 a HttpException.

Therefore the correct solution becomes:

protected void Application_PostAcquireRequestState(object sender, EventArgs e){    if (Context.Handler is IRequiresSessionState)    {        log4net.ThreadContext.Properties["SessionId"] = Session.SessionID;    }}


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-87http://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):

protected void Application_PostAcquireRequestState(object sender, EventArgs e){    log4net.ThreadContext.Properties["SessionID"] = Session.SessionID;}

And add [%property{SessionID}] to conversionPattern.


I was looking answer for this too and found out that %aspnet-request{ASP.NET_SessionId} works fine for me.