Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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

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

1 Answer

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...