Reputation: 466
I have dynamically created game instances that each create a GUID on initialization, I want each of these instances to log in their own logfile. However right now it only logs to the latest instance initialized
Game Instance:
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");
}
}
My Nlog Configuration:
<?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>
Upvotes: 1
Views: 1004
Reputation: 750
You should use LogEventInfo instance and set it's property value instead of setting logger factory configuration variable
var logEventInfo = new LogEventInfo(logLevel, loggerName, message);
logEventInfo.Properties["GameGuid"] = Guid.NewGuid().ToString();
logger.Log(logEventInfo);
Instead of ${var:GameGuid}
use ${event-properties:item=GameGuid}
Upvotes: 3