3
votes

Recently I have been working on a project where, among other things, we want to provide a centralized configuration system. We are using WCF, Silverlight, C#, etc to create a distributed system of services and clients. One of the things that we will want to configure is logging. Obviously, we can configure log4net or NLog via the app.config or via a separate logging configuration file. We can also configure via code. I wanted to see if it was possible to configure via XML from code. In other words, imagine that you have in memory (maybe read from a database?) the entire XML required to configure either logging framework. Can it be done? Is it possible to configure log4net and/or NLog via a string containing a correctly formed (in the context of the particular logging framework) as opposed to reading from the file or via "conventional" API configuration?

I have figured out how to do it for each of these logging frameworks. I'm not sure that we will actually use it, but I thought that I would share it here on SO, just in case anyone else might find it useful. Also, feel free to comment on the advisability (or not) of configuring the logging frameworks this way.

Two obvious potential issues that I can think of are:

  1. It could be difficult to construct valid XML (or enter it in the database). My first guess is that one would define the XML that same way one would today. Put it in a app.config (or external config) file and then run a test program to verify that the XML yields the expected results.

  2. How easy or difficult (or impossible) will it be to update the XML in the database and then have the program/service/whatever react to the change (like using log4net's ConfigureAndWatch option)? I am not as interested in the mechanics of how a program or service would know that the XML has been updated. Let's just assume that the program will check the database periodically. Given a new XML string, it is easy enough to reconfigure the logging frameworks.

I will post my technique as an answer to this question.

1
Solution found here is much cleaner.juagicre

1 Answers

8
votes

Configure log4net via XML in code:

  string xml =
  @"<log4net>
    <appender name='file1' type='log4net.Appender.RollingFileAppender'>
      <!-- Log file locaation -->
      <param name='File' value='log4net.log'/>
      <param name='AppendToFile' value='true'/>
      <!-- Maximum size of a log file -->
      <maximumFileSize value='2KB'/>
      <!--Maximum number of log file -->
      <maxSizeRollBackups value='8'/>
      <!--Set rolling style of log file -->
      <param name='RollingStyle' value='Composite'/>
      <param name='StaticLogFileName' value='false'/>
      <param name='DatePattern' value='.yyyy-MM-dd.lo\g'/>
      <layout type='log4net.Layout.PatternLayout'>
        <param name='ConversionPattern' value='%d [%t] %-5p  %m%n'/>
      </layout>
    </appender>

    <!-- Appender layout fix to view in console-->
    <appender name='console' type='log4net.Appender.ConsoleAppender'>
      <layout type='log4net.Layout.PatternLayout'>
        <param name='Header' value='[Header]\r\n'/>
        <param name='Footer' value='[Footer]\r\n'/>
        <param name='ConversionPattern' value='%d [%t] %-5p  %m%n'/>
      </layout>
    </appender>

    <appender name='debug' type='log4net.Appender.DebugAppender'>
      <layout type='log4net.Layout.PatternLayout'>
        <param name='ConversionPattern' value='%d [%t] %logger %-5p %m%n'/>
      </layout>
    </appender>
    <root>
      <level value='INFO'/>
      <!--
            Log level priority in descending order:

            FATAL = 1 show  log -> FATAL 
            ERROR = 2 show  log -> FATAL ERROR 
            WARN =  3 show  log -> FATAL ERROR WARN 
            INFO =  4 show  log -> FATAL ERROR WARN INFO 
            DEBUG = 5 show  log -> FATAL ERROR WARN INFO DEBUG
            -->
      <!-- To write log in file -->
      <appender-ref ref='debug'/>
      <appender-ref ref='file1'/>
    </root>

  </log4net>";

  XmlDocument doc = new XmlDocument();
  doc.LoadXml(xml);

  log4net.Config.XmlConfigurator.Configure(doc.DocumentElement);

Configure NLog via XML in code (works for NLog 2.0 and later):

  string xml = @"<nlog> 
                   <targets> 
                     <target name='console' type='Console' layout='${message}' /> 
                   </targets> 

                   <rules> 
                     <logger name='*' minlevel='Error' writeTo='console' /> 
                   </rules> 
                 </nlog>"; 

  StringReader sr = new StringReader(xml); 
  XmlReader xr = XmlReader.Create(sr); 
  XmlLoggingConfiguration config = new XmlLoggingConfiguration(xr, null); 
  LogManager.Configuration = config; 
  //NLog is now configured just as if the XML above had been in NLog.config or app.config

Prior to NLog 2.0, NLog's XmlLoggingConfiguration object does not take an XmlReader in its constructor. You can pass an XmlElement instead, like this:

  string xml = @"<nlog>  
               <targets>  
                 <target name='debugger' type='Console' layout='${message}' />  
               </targets>  

               <rules>  
                 <logger name='*' minlevel='Error' writeTo='console' />  
               </rules>  
             </nlog>";

  XmlDocument doc = new XmlDocument();
  doc.LoadXml(xml);

  XmlLoggingConfiguration config = new XmlLoggingConfiguration(doc.DocumentElement,null);
  LogManager.Configuration = config;

To update the configuration, given a new XML string, simply repeat the steps for the particular logging framework that you are using.