首页 > 解决方案 > NLog:在运行时从模板生成配置

问题描述

我正在尝试基于另一个目标在运行时生成目标和记录器。假设我有一个功能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.1, Foo.2, ...),等等AllTargets。但是当我使用返回的记录器进行记录时,没有创建任何文件,而且完全就像什么都没发生一样......

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

谢谢你的帮助!

标签: c#nlognlog.config

解决方案


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


推荐阅读