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:
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.
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.
Configure log4net via XML in code:
Configure NLog via XML in code (works for NLog 2.0 and later):
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:
To update the configuration, given a new XML string, simply repeat the steps for the particular logging framework that you are using.