This is probably not possible, but I’m wondering if there’s a way to make it work.
I have a large ASP.NET MVC43 application that is already instrumented with logging statements.
Now we need to include a “Company Name” value from the Session object in each log entry. Is it possible to configure log4net to read Session data and include it in the log entry? Or some way to force it to…?
Thanks for any ideas.
[Edit]
This question helped a lot: How can I include SessionID in log files using log4net in ASP.NET?
I ended up with this as my solution:
In Global.asax.cs:
// After the session is acquired, push the organization code into log4net's thread context, in case it has to log anything.
protected void Application_PostAcquireRequestState(object sender, EventArgs e)
{
if (Context.Handler is IRequiresSessionState && Session != null && Session[Constants.EMPLOYEE_DETAILS] != null)
log4net.ThreadContext.Properties["Company"] = ((EmployeeDetails)Session[Constants.EMPLOYEE_DETAILS]).Company;
}
In log4net configuration:
<parameter>
<parameterName value="@Company"/>
<dbType value="String"/>
<size value="10"/>
<layout type="log4net.Layout.PatternLayout">
<conversionPattern value="%property{Company}" />
</layout>
</parameter>
Works great – I get a company name in my log output now. Thanks for the help, everyone.
See this answer for some ideas on how you can implement this.
Capture username with log4net
You should be able to do it without implementing your own Appender.
Here is an example of a custom
PatternLayoutConverterthat pulls a parameterized value fromHttpContext.Current.Session. (I don’t remember if tested it when I posted as part of the linked answer or not, but it should be close):Another simpler idea would be to do something like this… Create an object that will retrieve the Session parameter you want and put that object in the MDC, then reference the MDC in your layout. When log4net accesses the object from the MDC, it will call its ToString method to get the value to be written to the log.
Use it like this somewhere near the entry point of your program:
(I don’t have an example handy for how to configure log4net to pull a parameter from the MDC, but it should not be hard to find one).
EDIT:
You could configure your PatternLayout something like this:
Now, assuming that
HttpContext.Session["Company Name"]is set to something, whenever you log a message, the value will be written to the log.