NLog用户特定的日志文件

时间:2013-06-30 07:22:19

标签: nlog

如何使用NLog创建用户特定的日志文件,其文件名等同于用户名?我知道您可以在布局中使用变量,但文件名属性设置在目标级别。我希望能够在filename="C:\pathtologfiles\${myApp:user}.txt"和调用类ClassLogger.Debug("user did something", thisUser.Username)中执行类似的操作。

1 个答案:

答案 0 :(得分:1)

以下是我最终如何做到这一点(很遗憾,在VB中)。你当然需要实现自己的_UsernameIsMeaningfulInThisContext_GetUsername

在nlog配置

<variable name="AppLogDir" value="C:\inetpub\ApplicationLogging\MyApplication" />
...
<targets>
  ...
  <target name="UserSpecificLogfile"
          xsi:type="File"
          fileName="${AppLogDir}\Users\AppUser_${event-context:item=AppUsername}.txt"
          createDirs="true" />
</targets>
<rules>
  ...
  <logger name="*" minLevel="Trace" maxLevel="Fatal" writeTo="UserSpecificLogfile" />
</rules>

在致电课程

Private Property _ClassLogger As Logger = LogManager.GetCurrentClassLogger()
...
Private Sub _LogMaybeUser(ByVal nLogLevel As NLog.LogLevel, ByVal nMsg As String)
{
     Dim logfileUser As String = "Unknown"
     If _UsernameIsMeaningfulInThisContext() { logfileUser = _GetUsername() }
     Dim logInfo As New LogEventInfo(nLogLevel, "", nMsg)
     logInfo.Properties("AppUsername") = logfileUser
     ClassLogger.Log(logInfo)
}