Capture username with log4net

后端 未结 6 1274
忘了有多久
忘了有多久 2020-11-27 17:05

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:

HttpConte         


        
6条回答
  •  猫巷女王i
    2020-11-27 17:42

    According to Log4Net official API docs, MDC is deprecated:

    The MDC is deprecated and has been replaced by the Properties. The current MDC implementation forwards to the ThreadContext.Properties.

    Other than that MDC.Set only accept strings as values, so the last solution from @wageoghe cannot work (the one that uses HttpContextUserNameProvider)

    My solution has been to use HttpContextUserNameProvider with log4net.GlobalContext, also suggested in official API docs:

    • Add this immediatley after log4net initialization (for example in Global.Application_Start)

      log4net.GlobalContext.Properties["user"] = new HttpContextUserNameProvider();
      
    • Add this class

      public class HttpContextUserNameProvider
      {
          public override string ToString()
          {
              HttpContext context = HttpContext.Current;
              if (context != null && context.User != null && context.User.Identity.IsAuthenticated)
              {
                  return context.User.Identity.Name;
              }
              return "";
          }
      }
      
    • Modify log4net configuration by adding the "user" property value, for example:

      
      

提交回复
热议问题