Nlog基于变量保存日志文件

时间:2017-07-17 08:04:18

标签: c# nlog

我已经动态创建了游戏实例,每个实例都在初始化时创建GUID,我希望每个实例都登录自己的日志文件。但是现在它只记录到最新的实例初始化

游戏实例:

public class GameInstance
{
    private static readonly Logger Logger = LogManager.GetCurrentClassLogger();

    public void Initialize()
    {
        var Guid = Guid.NewGuid();
        Logger.Factory.Configuration.Variables["GameGuid"] = Guid.ToString();
        Logger.Info("Game starting, GUID: " + Guid + ", with " + AllUsers.Count + " players.");    
    }

    public void HandleUserInput()
    {
        Logger.Info("Test Test");
    }
}

我的Nlog配置:

<?xml version="1.0" encoding="utf-8" ?>
<nlog xmlns="http://www.nlog-project.org/schemas/NLog.xsd"
      xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
      xsi:schemaLocation="http://www.nlog-project.org/schemas/NLog.xsd NLog.xsd"
      autoReload="true"
      throwExceptions="false"
      internalLogLevel="Off" internalLogFile="c:\temp\nlog-internal.log">

  <targets>
    <target name="logfile" xsi:type="File" fileName="logs/logfile.txt" />
    <target name="gamefile" xsi:type="File" fileName="logs/games/${var:GameGuid}.txt" />
  </targets>

  <rules>
    <logger name="Test.GameInstance" minlevel="Info" writeTo="gamefile" final="true"/>
    <logger name="*" minlevel="Info" writeTo="logfile" />
  </rules>
</nlog>

1 个答案:

答案 0 :(得分:3)

您应该使用LogEventInfo实例并设置它的属性值,而不是设置logger factory配置变量

var logEventInfo = new LogEventInfo(logLevel, loggerName, message);
logEventInfo.Properties["GameGuid"] = Guid.NewGuid().ToString();

logger.Log(logEventInfo);

而不是${var:GameGuid}使用${event-properties:item=GameGuid}