gpt4 book ai didi

c# - 在运行时更新 NLog 目标文件名

转载 作者:IT王子 更新时间:2023-10-29 04:38:08 25 4
gpt4 key购买 nike

在我的申请中,我每天处理几千份文件。在某些情况下,我想要一些日志,一个文档的日志。然后我想针对特定目标在运行时更改输出文件名(并且仅更改文件名)。

我在网上找到了如何通过编程来创建目标 我只想通过编程更新文件名。我尝试了下面的代码。我收到的错误是“找不到 LayoutRender 'logDirectory'。

有什么想法吗?

谢谢,

var target = (FileTarget)LogManager.Configuration.FindTargetByName("logfile");
target.FileName = "${logDirectory}/file2.txt";

LoggingConfiguration config = new LoggingConfiguration();
var asyncFileTarget = new AsyncTargetWrapper(target);
config.AddTarget("logfile", asyncFileTarget);

LogManager.Configuration = config;

配置文件是:

  <nlog xmlns="http://www.nlog-project.org/schemas/NLog.xsd" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
<variable name="logDirectory" value="C:/MyLogs"/>
<targets>
<target name="logfile" xsi:type="File" layout="${date:format=dd/MM/yyyy HH\:mm\:ss.fff}|${level}|${stacktrace}|${message}" fileName="${logDirectory}/file.txt" />
</targets>

<rules>
<logger name="*" minlevel="Info" writeTo="logfile" />
</rules>
</nlog>

最佳答案

尝试ReconfigExistingLoggers方法:

var target = (FileTarget)LogManager.Configuration.FindTargetByName("logfile");
target.FileName = "${logDirectory}/file2.txt";
LogManager.ReconfigExistingLoggers();

如文档中所写:

Loops through all loggers previously returned by GetLogger. and recalculates their target and filter list. Useful after modifying the configuration programmatically to ensure that all loggers have been properly configured.

编辑:

尝试使用自定义布局渲染器:NLog config file to get configuration setting values from a web.config

关于c# - 在运行时更新 NLog 目标文件名,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20756777/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com