Log4Net - Can I have a custom section name in Config

I need to use a section name other than log4net in the configuration section. I know that we usually use

<section name="log4net" type="log4net.Config.Log4NetConfigurationSectionHandler,log4net" /> 

But I need to have such a section

 <section name="log2net" type="log4net.Config.Log4NetConfigurationSectionHandler,log4net" /> 

I am working on a sitecore site and has its own Sitecore.Logging dll, which is also derived from log4net. So the dll Sitecore Logging refers to the log4net section in web.config

We have our custom app log4net, which only works with log4net and not with sitecore.logging dll. Therefore, I thought that I could have two loggers in my project, sitecore.logger and log4net logger. Sitecore.logger uses the log4net section, so I wanted log4net to use another anme section like log2net

I tried using the code below using the log2net section in config.

But I get the error log4net: ERROR XmlHierarchyConfigurator: the Xml element is not a log4net element.

  XmlElement element = (XmlElement)ConfigurationManager.GetSection("log2net"); log4net.Config.XmlConfigurator.Configure(element); 

Can someone help.

+6
source share
1 answer

I could not reproduce the exception that you are experiencing, but looking at its details and the code of the XmlHierarchyConfigurator class , the exception occurs when the name of the root xml element is not log4net , and this is exactly what you are trying to do.

What you can do is:

  • Read your own log2net XmlElement
  • Create a new log4net XmlElement
  • Copy all the children of your log2net to the new log4net element
  • Run the XmlConfigurator.Configure() method, passing in your new log4net element.
 XmlElement element = (XmlElement)ConfigurationManager.GetSection("log2net"); XmlElement newLog4net = element.OwnerDocument.CreateElement("log4net"); for (int i = 0; i < element.ChildNodes.Count; i++) { XmlNode child = element.ChildNodes[i]; newLog4net.AppendChild(child.CloneNode(true)); } log4net.Config.XmlConfigurator.Configure(newLog4net); 
+4
source

Source: https://habr.com/ru/post/954207/


All Articles