在运行时让NLog配置文件由用户定义

4

我有一个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>
1个回答

5
您可以通过名称从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);

你的意思是说没有办法在运行时更新NLog配置文件,例如从numericupdown值? - user2968369
嗯,有趣。我从未使用过 LINQ。如果我在添加 System.Xml.Linq 命名空间后只是复制粘贴此代码到我的项目中,它应该可以工作吗? - user2968369
1
@user2968369 可能你忘记了命名空间,或者目标有不同的名称。 - Sergey Berezovskiy
谢谢,它有所帮助。 http://stackoverflow.com/questions/20243576/a-factor-while-making-at-runtime-nlog-config-user-define我还有另一个问题,我已经在一个新线程中提出,以保持stackoverflow社区的更有条理 :). 如果您能对此进行补充,那将非常棒。 - user2968369

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接