Editing Log4NET Configuration Programatically

There are two input Xelement provides: the first one doesn’t exist in the source and the other one exists but with different attribute values. The output file will have all the existing elements and will include the updated values provided in inputs.

I have a situation where I need to output logs generated by a specific class in a separate file. And there are lots of services in which it needs to be changed across many machines. So I need a utility which can do so programatically. We basically need to add an appender and a logger to all log4net configuration files.

I will specifically focus on how to change config files, this is part of a larger utility.

Suppose we provide this input.
  1. <loggername="LoggerName">  
  2. <levelvalue="DEBUG" />  
  3. <appender-refref="ConsoleAppender" />  
  4. </logger>  
  5. First we create XmlDocument from the input string. And then we extract attributes which needs to be updated.  
  6. privatevoid AppendConfigLog4net(string text1nput)  
  7. {  
  8. text1nput = ClearTextFromInvalidChars(text1nput);  
  9.   
  10. XDocument xmlDoc1 = XDocument.Parse(text1nput, LoadOptions.None);  
  11.   
  12. foreach (var v1 in xmlDoc1.Descendants())  
  13. {  
  14. if (string.Compare(v1.Name.LocalName, "appender"true) == 0)  
  15. {  
  16. AddAndReplaceAppenderElementInExisitngConfig(v1, v1.Attribute("name").Value, v1.Element("file").Attribute("value").Value);  
  17. }  
  18. elseif (string.Compare(v1.Name.LocalName, "logger"true) == 0)  
  19. {  
  20. AddorReplaceLoggerElementInExisitngConfig(v1, v1.Attribute("name").Value, v1.Element("appender-ref").Attribute("ref").Value);  
  21. }  
  22. }  
  23. }  
Then in the existing config file we load in XmlDocument and replace attributes or add new element if it weren’t existing.
  1. privatevoid AddorReplaceLoggerElementInExisitngConfig(XElement v1, string localName, string value)  
  2. {  
  3.     var query = from c in xDoc.Root.Descendants("logger")  
  4.     where(string) c.Attribute("name") == localName  
  5.     select c;  
  6.     if (query.Count() <= 0)   
  7.     {  
  8.         var v2 = xDoc.Root.Descendants("logger").LastOrDefault();  
  9.         xDoc.Root.Add(newXElement(v1));  
  10.     } else foreach(XElement node in query)  
  11.     {  
  12.         if ((string) node.Element("appender-ref").Attribute("ref") != value)   
  13.         {  
  14.             node.Element("appender-ref").Attribute("ref").Value = value;  
  15.         }  
  16.     }  
  17. }  
Attached working project has all the details.