log4net AdoNetAppender with bufferSize>1 and a pattern containing "aspnet-session"

StackOverflow https://stackoverflow.com/questions/23668542

  •  23-07-2023
  •  | 
  •  

سؤال

I'm using log4net in a ASP.NET MVC application. I want to log to the database and am using AdoNetAppender with a bufferSize=10 to reduce the load on the database.

I also want to capture some session variables e.g. username. I can do this with a pattern like so:

%aspnet-session{username}

The problem is that the session values seem to be evaluated when the buffer is filled, not when the entry is logged, so I get 10 log entries with the same username even through each log entry was created by a different user.

This problem also effects calculated properties - i.e. the calculated property is evaluated when the buffer is filled, not when the entry is loggedd.

This is not a problem if bufferSize=1 because each log entry is logged, evaluated and written at the same time.

Is there a way to evaluate the session variables when the item is logged and buffer the log entries?

هل كانت مفيدة؟

المحلول

In Application_PostAcquireRequestState, set the username via the ThreadContext:

protected void Application_PostAcquireRequestState(object sender, EventArgs e)
{
     // Make sure there's a Session in this request if you need it
     if (Context.Handler is IRequiresSessionState)
     {
         var username = Session["UserName"];
         log4net.ThreadContext.Properties["username"] = username ;
     }
}

Then, in your config file you have this:

<layout type="log4net.Layout.PatternLayout">
    <conversionPattern value="%property{username}" />
</layout>
مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top