添加/运行时NLOG过程中删除日志文件过程中、文件、日志、NLOG

由网友(两面人@)分享简介:我正在写一个小的文件转换工具。当它们被丢弃到一个目录中的文件被自动转换。I'm writing a small file conversion utility. Files get automatically converted when they are dropped into a directory.我使用N...

我正在写一个小的文件转换工具。当它们被丢弃到一个目录中的文件被自动转换。

I'm writing a small file conversion utility. Files get automatically converted when they are dropped into a directory.

我使用NLOG进行记录。除了这是使用配置中央日志文件中的 NLog.conf 的(和接收生成的所有消息),我想为每个输入文件一个额外的日志文件,具有类似名称,并包含所有登录在转换过程中写入消息。

I'm using NLog for logging. Besides a central log file which is configured using NLog.conf (and which receives all messages generated), I'd like to create one additional log file for each input file, having a similar name and containing all log messages written during the conversion process.

不幸的是我似乎无法找出如何正确地与运行时相应的规则添加新的文件的目标。我希望所有的日志对象在转换过程中写入新的日志文件。

Unfortunately I seem to be unable to find out how to properly add a new file target together with the appropriate rule during runtime. I want all Logger objects to write to the new log file during the conversion process.

我想是这样

var logfile = new NLog.Targets.FileTarget();
logfile.FileName = fileName + ".log";
logfile.KeepFileOpen = true;
logfile.Initialize();
var rule = new NLog.Config.LoggingRule("*", logfile);
NLog.LogManager.Configuration.LoggingRules.Add(rule);
NLog.LogManager.ReconfigExistingLoggers();
//
// Proceed with converting file
//
logfile.Flush();
NLog.LogManager.Configuration.LoggingRules.Remove(rule);
NLog.LogManager.ReconfigExistingLoggers();

但是,没有日志文件被创建。

But no log file was created.

我是怎么了?你知道吗?

What did I wrong? Any idea?

推荐答案

在此线程的第二个职位使我的解决方案: http://nlog-project.org/forum.html#nabble-td1685349

The second post on this thread led me to the solution: http://nlog-project.org/forum.html#nabble-td1685349

您必须得到当前NLOG配置,更改此LoggingConfiguration对象,然后又重新分配给LogManager.Configuration。

You have to get the current NLog configuration, make changes to this LoggingConfiguration object, then assign it back to LogManager.Configuration.

这是在code我用:

LoggingConfiguration config = LogManager.Configuration;

var logFile = new FileTarget();
config.AddTarget("file", logFile);

logFile.FileName = fileName + ".log";
logFile.Layout = "${date} | ${message}";

var rule = new LoggingRule("*", LogLevel.Info, logFile);
config.LoggingRules.Add(rule);

LogManager.Configuration = config;

logger.Info("File converted!");
阅读全文

相关推荐

最新文章