本文介绍了如何使用Log4Net在日志文件中获取当前用户名而不是AppPool身份的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我们正在使用ASP.NET MVC3应用程序中的Log4Net,一切正常,但是我们希望在日志文件中看到当前的用户名而不是应用程序池的标识,这是我们正在使用的附加程序配置:

 <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>
 

因此,似乎该属性:%username正在检索以下值:

WindowsIdentity.GetCurrent().Name

代替我们所需要的:HttpContext.Current.User

关于如何在不创建自定义属性或其他log4net派生类的情况下如何轻松地在web.config中解决此问题的想法?如果可能的话,否则,如果自定义属性是我们生活的唯一方式,我想:)谢谢!

解决方案

%identity替换%username应该可以.在我当前的项目中,它正在为我工​​作.

您可以通过 优秀教程了解更多有关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!

解决方案

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

这篇关于如何使用Log4Net在日志文件中获取当前用户名而不是AppPool身份的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

11-02 11:40