c# - NLog:在运行时从模板生成配置
问题描述
我正在尝试基于另一个目标在运行时生成目标和记录器。假设我有一个功能Foo
记录器:我想为Foo.1
、Foo.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
。但是当我使用返回的记录器进行记录时,没有创建任何文件,而且完全就像什么都没发生一样......
我已经尝试了这个线程中提出的解决方案,但没有成功......我错过了什么?
谢谢你的帮助!
解决方案
实际上,这是一个非常愚蠢的错误,因为这可能会按我的预期工作。问题在于它baseTarget.FileName
是一个Layout
对象,并且通过在输出 ( ) 中.ToString()
添加引号来进行错误转换的字符串化。'C:\...'
因此,NLog 抛出了错误,这些错误被 NLog 配置部分掩盖了,而且无论如何都很难理解。baseTarget.FileName
我通过检查是否是一个SimpleLayout
(在我的情况下我必须处理的唯一类)来修复它,然后OriginalText
从该布局中检索出。然后,它就像一个魅力。
推荐阅读
- ios - 子视图的边界在 layoutSubviews() 中为零
- node.js - 第二个axios post请求不发送
- emacs - 如何扩展 Neotree 以使用 hexl 打开文件?
- c# - 在 C# 中对 char 数组中的 double 进行编码
- android - 设置 sqflite 数据库表时缺少列
- python - 如何选择与我的模型相关的模型对象
- java - 我怎样才能以某种方式在 Spring-Boot 程序中“存储”一个 json 文件,以便我的 web 应用程序读取这个 json
- javascript - 如何让我的函数在返回另一个调用之前等待
- actions-on-google - 无法通过 Google Actions 中的 Google 电子表格上传内容
- python - 我们可以为 Flow 项目中的每个车道选择最大和最小速度吗?