【问题标题】:NLog: Generate configurations at runtime from templateNLog:在运行时从模板生成配置
【发布时间】:2019-03-16 15:25:50
【问题描述】:

我正在尝试根据另一个目标在运行时生成目标和记录器。假设我有一个功能 Foo 记录器:我想为 Foo.1Foo.2 等生成单独的规则,但我不知道我必须创建的最后一个记录器是什么(因此,我不能以声明方式定义它们)。

到目前为止,我做了这样的事情:

public GetNewClonedLogger(int fooId)
{
    var config = NLog.LogManager.Configuration;
    var newFooName = $"Foo.{fooId}";
    FileTarget baseTarget = NLog.LogManager.Configuration.FindTargetByName<FileTarget>("Foo");

    // Copy the base target
    var newTarget = new FileTarget(newFooName)
    {
        Layout = baseTarget.Layout,
        CreateDirs = true,
        FileName = baseTarget .FileName.ToString().Replace("${var:filename}", newFooName),
        ArchiveAboveSize = baseTarget.ArchiveAboveSize,
        BufferSize = baseTarget.BufferSize,
        ArchiveFileName = baseTarget.ArchiveFileName,
        MaxArchiveFiles = baseTarget.MaxArchiveFiles,
        ArchiveDateFormat = baseTarget.ArchiveDateFormat,
        ArchiveEvery = baseTarget.ArchiveEvery,
        FileAttributes = baseTarget.FileAttributes,
        KeepFileOpen = baseTarget.KeepFileOpen,
        ArchiveNumbering = baseTarget.ArchiveNumbering,
    };

    // Add configs & flush
    NLog.LogManager.Configuration.AddTarget(newTarget);
    NLog.LogManager.Configuration.AddRuleForAllLevels(newTarget, newFooName);

    // I tried every combinations of the following, without success
    NLog.LogManager.ReconfigExistingLoggers();
    NLog.LogManager.Configuration = config;
    NLog.LogManager.Configuration.Reload();

    NLog.LogManager.GetLogger(newFooName);
}

此函数返回一个记录器,在每个点上似乎都可以:目标名称正常,文件名正常,NLog.LogManager.Configuration 有一个具有正确名称的新规则(Foo.1Foo.2、.. .),AllTargets 也是如此。但是当我使用返回的记录器进行记录时,没有创建任何文件,而且完全就像什么都没发生一样......

我已经尝试了this thread 中提出的解决方案,但没有成功......我错过了什么?

感谢您的帮助!

【问题讨论】:

  • 我认为我们可以让这个工作,但我怀疑你是否真的想要这个。什么情况下需要这个?目标的很多属性都是可模板化的,因此大多数时候不需要动态规则和目标。
  • 另请注意,更改(全局)配置不是线程安全的。
  • 我必须将模板配置与其他一些来源(例如数据库来源的配置)合并。我们知道这种方法的线程不安全方面,因此我们在需要时使用lock 关键字实现了我们的实际记录器生成。另外,我解决了这个问题(见下文),但感谢您的建议

标签: c# nlog nlog.config


【解决方案1】:

实际上,这是一个非常愚蠢的错误,因为这可能会按我的预期工作。问题是baseTarget.FileName 是一个Layout 对象,而使用.ToString() 的字符串化通过在输出中添加引号('C:\...') 进行了错误的转换。因此,NLog 抛出了错误,这些错误被 NLog 配置部分忽略了,而且无论如何都很难理解。我通过检查baseTarget.FileName 是否是SimpleLayout(在我的情况下我必须处理的唯一类)来修复它,然后从该布局中检索OriginalText。然后,它就像一个魅力。

【讨论】:

    猜你喜欢
    • 2012-04-07
    • 1970-01-01
    • 2012-08-18
    • 1970-01-01
    • 2017-05-05
    • 1970-01-01
    • 2018-05-17
    • 1970-01-01
    相关资源
    最近更新 更多