title: Capture username with log4net
body: <p>I currently write all log4net events to a database, and it seems to work just fine. To capture the logged in user account I use this piece of code:</p>
  
  <pre><code>HttpContext context = HttpContext.Current;
  if (context != null &amp;&amp; context.User != null &amp;&amp; context.User.Identity.IsAuthenticated)
  {
      MDC.Set("user", HttpContext.Current.User.Identity.Name);
  }
  </code></pre>
  
  <p>The code seems ok, except for events that have no user context associated with them (ie. a user on our public web page). In that case the log4net capture seems to sometime write the last logged in user account (bad) and sometime write a null (good). Anyone got this feature to work reliably in all cases? I believe I saw a note that MDC is no longer a recommended feature to use, but I wasn't able to find any alternatives that are recommended.</p>
  
  <p>Note: I find it odd that MDC is set with an account name, but never cleared if no user is active. That could be part of the problem. However, I didn't find any MDC code extracts that also clear the username.</p>