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