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 out
Tony's solution doesn't seem to work if you use NLog Async (). I had to use the wrapper target to get my FileTarget, otherwise I get a lot of errors. I'm using NLog 2.1.
if (LogManager.Configuration != null && LogManager.Configuration.ConfiguredNamedTargets.Count != 0)
{
Target target = LogManager.Configuration.FindTargetByName("yourFileName");
if (target == null)
{
throw new Exception("Could not find target named: " + "file");
}
FileTarget fileTarget = null;
WrapperTargetBase wrapperTarget = target as WrapperTargetBase;
// Unwrap the target if necessary.
if (wrapperTarget == null)
{
fileTarget = target as FileTarget;
}
else
{
fileTarget = wrapperTarget.WrappedTarget as FileTarget;
}
if (fileTarget == null)
{
throw new Exception("Could not get a FileTarget from " + target.GetType());
}
fileTarget.FileName = "SetFileNameHere";
LogManager.ReconfigExistingLoggers();
}
This also doesn't change the config file, it just changes the runtime value. So I also manually edit the config file to my new value using the code below:
var nlogConfigFile = "NLog.config";
var xdoc = XDocument.Load(nlogConfigFile);
var ns = xdoc.Root.GetDefaultNamespace();
var fTarget = xdoc.Descendants(ns + "target")
.FirstOrDefault(t => (string)t.Attribute("name") == "yourFileName");
fTarget.SetAttributeValue("fileName", "SetFileNameHere");
xdoc.Save(nlogConfigFile);