Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
381 views
in Technique[技术] by (71.8m points)

c# - Add / remove logfiles during runtime in NLog

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

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.

I tried something like

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

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

This is the code I used:

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!");

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...