【问题标题】:Making NLog config file user define at run time使 NLog 配置文件用户在运行时定义
【发布时间】:2013-11-26 23:04:18
【问题描述】:

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

【问题讨论】:

    标签: c# logging nlog


    【解决方案1】:

    您可以从 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 值?
    • hmm 很有趣.. 我从未使用过 LINQ。如果我只是在添加 System.Xml.Linq 命名空间后将此代码复制粘贴到我的项目中,它应该可以工作吗?
    • @user2968369 可能你忘记了命名空间,或者你的目标名称不同
    • 感谢它的帮助。 stackoverflow.com/questions/20243576/… 我在一个新线程中提出了另一个问题,以使 stackoverflow 的世界更有条理:)。如果您可以为此添加一些东西,那将是非常棒的
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-07-12
    • 1970-01-01
    • 2019-03-16
    • 2011-01-28
    • 1970-01-01
    • 2021-01-12
    • 1970-01-01
    相关资源
    最近更新 更多