NLog:如何根据环境变量有条件 select 目标
NLog : How to conditional select target based on env variable
我想在 nlog 中定义 2 个目标(通常是 Devops 上的文件目标和本地的 UDP)并根据位置动态选择它们。这样做的动机是在本地 运行 和 Devops 运行 时使用不同的目标。
有很多文章介绍如何使用 C# 代码执行此操作,但我想知道是否可以直接在配置文件中执行此操作。
在伪代码中,我在我的规则部分寻找这样的东西:
<rules>
if(Env==DEVOPS)
<logger name="*" minlevel="Info" writeTo="file" />
else
<logger name="*" minlevel="Trace" writeTo="udp" />
end
</rules>
我建议你使用这里描述的方法:
<nlog>
<variable name="myFileLevel" value="Off" />
<variable name="myUdpLevel" value="Off" />
<rules>
<logger name="*" minLevel="${var:myFileLevel}" writeTo="file" />
<logger name="*" minLevel="${var:myUdpLevel}" writeTo="udp" />
</rules>
</nlog>
然后在运行时执行此操作:
if (DevOps)
{
LogManager.Configuration.Variables["myFileLevel"] = "Debug";
}
else
{
LogManager.Configuration.Variables["myUdpLevel"] = "Trace";
}
LogManager.ReconfigExistingLoggers();
另请参阅:https://github.com/nlog/NLog/wiki/Filtering-log-messages#semi-dynamic-routing-rules
我想在 nlog 中定义 2 个目标(通常是 Devops 上的文件目标和本地的 UDP)并根据位置动态选择它们。这样做的动机是在本地 运行 和 Devops 运行 时使用不同的目标。
有很多文章介绍如何使用 C# 代码执行此操作,但我想知道是否可以直接在配置文件中执行此操作。
在伪代码中,我在我的规则部分寻找这样的东西:
<rules>
if(Env==DEVOPS)
<logger name="*" minlevel="Info" writeTo="file" />
else
<logger name="*" minlevel="Trace" writeTo="udp" />
end
</rules>
我建议你使用这里描述的方法:
<nlog>
<variable name="myFileLevel" value="Off" />
<variable name="myUdpLevel" value="Off" />
<rules>
<logger name="*" minLevel="${var:myFileLevel}" writeTo="file" />
<logger name="*" minLevel="${var:myUdpLevel}" writeTo="udp" />
</rules>
</nlog>
然后在运行时执行此操作:
if (DevOps)
{
LogManager.Configuration.Variables["myFileLevel"] = "Debug";
}
else
{
LogManager.Configuration.Variables["myUdpLevel"] = "Trace";
}
LogManager.ReconfigExistingLoggers();
另请参阅:https://github.com/nlog/NLog/wiki/Filtering-log-messages#semi-dynamic-routing-rules