我有一个winForm应用程序。我正在使用NLog进行日志记录。我的配置文件如下。我可以在运行时在此配置文件中定义任何参数吗?例如对于archiveAboveSize="4000"
我可以在winform中有一个numericupdown,它可以从用户那里获取此值(以便4000可以是3000或5000),然后在配置文件中相应地设置此值?
<?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">
<targets>
<target xsi:type="File"
name="file"
layout="${longdate}|${level:uppercase=true}|${logger}|${message}"
archiveAboveSize="4000"
maxArchiveFiles="1"
archiveFileName="${basedir}/log_archived.txt"
fileName="log.txt" />
</targets>
<rules>
<logger name="*" minlevel="Info" writeTo="file" />
</rules>
</nlog>
您可以从NLog配置中按名称获取目标并在运行时更改设置:
var target = (FileTarget)LogManager.Configuration.FindTargetByName("file");
if (target != null)
target.ArchiveAboveSize = 3000;
不幸的是,您不能以这种方式更新NLog配置文件-您应该手动进行。您可以为此使用LINQ:
var nlogConfigFile = "NLog.config";
var xdoc = XDocument.Load(nlogConfigFile);
var ns = xdoc.Root.GetDefaultNamespace();
var fileTarget = xdoc.Descendants(ns + "target")
.FirstOrDefault(t => (string)t.Attribute("name") == "file");
fileTarget.Attribute("archiveAboveSize").SetValue(3000);
xdoc.Save(nlogConfigFile);
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句