Reputation: 275
I have a winForm app. I am using NLog for logging purpose. My config file is below. Can I make any paramter in this config file user define at run time. e.g for archiveAboveSize="4000"
can I have a numericupdown in winform which can take input this value from user (so that 4000 can be 3000 or 5000) and then set this value in config file accordingly ?
<?xml version="1.0" encoding="utf-8" ?>
<nlog xmlns="http://www.nlog-project.org/schemas/NLog.xsd"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
<targets>
<target xsi:type="File"
name="file"
layout="${longdate}|${level:uppercase=true}|${logger}|${message}"
archiveAboveSize="4000"
maxArchiveFiles="1"
archiveFileName="${basedir}/log_archived.txt"
fileName="log.txt" />
</targets>
<rules>
<logger name="*" minlevel="Info" writeTo="file" />
</rules>
</nlog>
Upvotes: 4
Views: 1777
Reputation: 236308
You can get target by name from NLog configuration and change settings at runtime:
var target = (FileTarget)LogManager.Configuration.FindTargetByName("file");
if (target != null)
target.ArchiveAboveSize = 3000;
Unfortunately you can't update NLog configuration file this way - you should do that manually. You can use LINQ for that:
var nlogConfigFile = "NLog.config";
var xdoc = XDocument.Load(nlogConfigFile);
var ns = xdoc.Root.GetDefaultNamespace();
var fileTarget = xdoc.Descendants(ns + "target")
.FirstOrDefault(t => (string)t.Attribute("name") == "file");
fileTarget.Attribute("archiveAboveSize").SetValue(3000);
xdoc.Save(nlogConfigFile);
Upvotes: 5