Nlog 根据变量保存日志文件
Nlog Save log file based on variable
我动态创建了游戏实例,每个实例都在初始化时创建了一个 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>
您应该使用 LogEventInfo 实例并设置它的 属性 值而不是设置记录器工厂配置变量
var logEventInfo = new LogEventInfo(logLevel, loggerName, message);
logEventInfo.Properties["GameGuid"] = Guid.NewGuid().ToString();
logger.Log(logEventInfo);
而不是 ${var:GameGuid}
使用 ${event-properties:item=GameGuid}
我动态创建了游戏实例,每个实例都在初始化时创建了一个 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>
您应该使用 LogEventInfo 实例并设置它的 属性 值而不是设置记录器工厂配置变量
var logEventInfo = new LogEventInfo(logLevel, loggerName, message);
logEventInfo.Properties["GameGuid"] = Guid.NewGuid().ToString();
logger.Log(logEventInfo);
而不是 ${var:GameGuid}
使用 ${event-properties:item=GameGuid}