在运行时更新NLog目标文件名 [英] Update NLog target filename at runtime

查看:301
本文介绍了在运行时更新NLog目标文件名的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我的应用程序中,我每天处理数千个文档.在某些情况下,我希望按文档记录一个日志.然后,我想为特定目标在运行时更改输出文件名(并且仅更改文件名).

In my application, I work on several thousand of document a day. I'd like, in some cases some logs, one log by document. Then I'd like for a specific target change the output filename (and only the filename) at runtime.

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

Around the web I found how to create a target by programming me I'd like just update a the filename by programming. I tried the code below. The error I receive is "LayoutRender cannot be found '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();

如文档中所述:

循环遍历以前由GetLogger返回的所有记录器.和 重新计算其目标和过滤器列表.修改后有用 以编程方式进行配置,以确保所有记录器均已 正确配置.

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配置文件以从web.config获取配置设置值

Try use custom layout renderer: NLog config file to get configuration setting values from a web.config

这篇关于在运行时更新NLog目标文件名的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆