Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get current username instead of AppPool identity in a logfile with Log4Net

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!

like image 367
Davide Piras Avatar asked Jul 18 '12 12:07

Davide Piras


People also ask

What is rolling file Appender in log4net?

RollingFileAppender can roll log files based on size or date or both depending on the setting of the RollingStyle property. When set to Size the log file will be rolled once its size exceeds the MaximumFileSize.


1 Answers

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

like image 73
Pierluc SS Avatar answered Oct 14 '22 22:10

Pierluc SS