How to get current username instead of AppPool ide

2019-04-19 13:23发布

问题:

We are using Log4Net from our ASP.NET MVC3 application, all works fine but we would like to see the current username instead of the application pool's identity in the log files, this is the appender configuration we are using:

<log4net>
    <appender name="FileAppender" type="log4net.Appender.RollingFileAppender">
      <threshold value="ALL" />
      <immediateFlush>true</immediateFlush>
      <lockingModel type="log4net.Appender.FileAppender+MinimalLock" />
      <encoding value="utf-8" />
      <file value="C:\Logs\MyLogs.log" />
      <appendToFile value="true" />
      <rollingStyle value="Date" />
      <maxSizeRollBackups value="30" />
      <maximumFileSize value="25MB" />
      <staticLogFileName value="true" />
      <layout type="log4net.Layout.PatternLayout">
        <conversionPattern value="[%property{log4net:HostName}] - %username%newline%utcdate - %-5level - %message%newline" />
      </layout>
    </appender>
    <root>
      <priority value="ALL" />
      <appender-ref ref="FileAppender" />
    </root>
</log4net>

So it seems like the property: %username is retrieving the value of:

WindowsIdentity.GetCurrent().Name

Instead of what we would need: HttpContext.Current.User

Any idea on how we can solve this easily in the web.config without creating custom properties or additional log4net derived classes? If possible at all otherwise if custom property is the only way we can live with that I guess :) thanks!

回答1:

Replacing %username by %identity should do it. It is working for me in my current project.

You can learn more about log4net with this excellent tutorial