Jon
Jon

Reputation: 1705

How can I programmatically update log4net configuration file?

I currently have the log4net config in the applications' app.config file, as such:

...
    <section name="log4net" type="log4net.Config.Log4NetConfigurationSectionHandler, log4net"/>
  </configSections>
  <log4net>
    <appender name="RollingLogFileAppender" type="log4net.Appender.RollingFileAppender">
      <file value="logs\Service.log"/>
      <appendToFile value="true"/>
      <rollingStyle value="Date"/>
      <datePattern value="yyyyMMdd"/>
      <layout type="log4net.Layout.PatternLayout">
        <conversionPattern value="%date [%thread] %-5level %logger - %message%newline"/>
      </layout>
    </appender>
    <appender name="ConsoleAppender" type="log4net.Appender.ConsoleAppender">
      <layout type="log4net.Layout.PatternLayout">
        <conversionPattern value="%date [%thread] %-5level %logger - %message%newline"/>
      </layout>
    </appender>
    <logger name="Data.WebService">
      <level value="ALL"/>
      <appender-ref ref="ConsoleAppender"/>
      <appender-ref ref="RollingLogFileAppender"/>
    </logger>
    <logger name="Data.Host.HostService">
      <level value="ALL"/>
      <appender-ref ref="ConsoleAppender"/>
      <appender-ref ref="RollingLogFileAppender"/>
    </logger>
  </log4net>

I know I can read this in via log4net.Config.XmlConfigurator.Configure();, however, I would like to be able to update it via some sort of call as well. I'll be accepting configuration from a web service and, once I've set the new config (currently only log level, but I'm not precluding other things being configurable down the road), I need to update what is in the config file.

Having all of the configs in one file is very convenient, however, I'm open to locating the config in another file if that makes it simpler.

Upvotes: 3

Views: 5450

Answers (2)

Jon
Jon

Reputation: 1705

Since there is no official method to do so, I wound up writing a method that uses xpath to locate the element(s) to change and then update accordingly. Works well enough for what I need to do and is more elegant than a brute-force "readinthefiletoastringthenreplacethetextthensavethestringtothefile" approach.

    public enum Log4NetConfigItem
    {
        LOGLEVEL
    }

    public const string LOG4NET_CONFIGFILE = "log4net.config";

    public void UpdateConfiguration(Log4NetConfigItem which, object value)
    {
        // Load the config file.
        XmlDocument doc = new XmlDocument();
        doc.Load(LOG4NET_CONFIGFILE);
        // Create an XPath navigator for the document.
        XPathNavigator nav = doc.CreateNavigator();

        try
        {
            XPathExpression expr;

            // Compile the correct XPath expression for the element we want to configure.
            switch (which)
            {
                default:
                case Log4NetConfigItem.LOGLEVEL:
                    // Compile a standard XPath expression
                    expr = nav.Compile("/configuration/log4net/logger/level");
                    break;
            }

            // Locate the node(s) defined by the XPath expression.
            XPathNodeIterator iterator = nav.Select(expr);

            // Iterate on the node set
            while (iterator.MoveNext())
            {
                XPathNavigator nav2 = iterator.Current.Clone();

                // Update the element as required.
                switch (which)
                {
                    default:
                    case Log4NetConfigItem.LOGLEVEL:
                        // Update the 'value' attribute for the log level.
                        SetAttribute(nav2, String.Empty, "value", nav.NamespaceURI, value.ToString());
                        break;
                }
            }

            // Save the modified config file.
            doc.Save(LOG4NET_CONFIGFILE);
        }
        catch (Exception ex) 
        {
            Console.WriteLine(ex.Message);
        }
    }

    void SetAttribute(System.Xml.XPath.XPathNavigator navigator, String prefix, String localName, String namespaceURI, String value)
    {
        if (navigator.CanEdit == true)
        {
            // Check if given localName exist
            if (navigator.MoveToAttribute(localName, namespaceURI))
            {
                // Exist, so set current attribute with new value.
                navigator.SetValue(value);
                // Move navigator back to beginning of node
                navigator.MoveToParent();
            }
            else
            {
                // Does not exist, create the new attribute
                navigator.CreateAttribute(prefix, localName, namespaceURI, value);
            }
        }
    }

Note: The SetAttribute code I got from here.

Upvotes: 6

weismat
weismat

Reputation: 7411

This is basically this open issue for log4net - unfortunately it is not resolved yet.

Upvotes: 0

Related Questions