2013-06-30 78 views
1

我怎样才能使用NLog创建用户特定的日志文件文件名相当于用户名?我知道你可以在布局中使用变量,但是文件名属性被设置在目标级别。我希望能够做到像filename="C:\pathtologfiles\${myApp:user}.txt"和呼叫类ClassLogger.Debug("user did something", thisUser.Username)NLog用户特定的日志文件

回答

0

下面是我如何完成它(不幸的是,在VB中)。你当然需要实现你自己的_UsernameIsMeaningfulInThisContext_GetUsername

在n日志配置

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