How can I configure log4net ILogs dynamically?

837 Views Asked by At

My application has a central log4net definition in its web.config, which I read with xmlConfigurator. Apart from that central logger, I need to define some other loggers that will write to various log files/DBs. The definitions for those loggers sit in my DB in xml format, and at runtime my attempt is to read them from DB, write them to a stream, configure them with XmlConfigurator as well and store them in an ILog collection (sb is a StringBuilder that contains the xml, logConfig.Type is the name of the logger as appears in xml):

byte[] byteArray = Encoding.UTF8.GetBytes(sb.ToString());
MemoryStream stream = new MemoryStream(byteArray);
log4net.Config.XmlConfigurator.Configure(stream);
ILog ilogRes = log4net.LogManager.GetLogger(logConfig.Type);
stream.Close();
return ilogRes;

ilogRes does not come configured as I expected (with the appenders defined in sb), but as the central logger. What am I doing wrong?

UPDATE: The initial problem was in my XML, once I removed a redundant element a new logger with a new appender was created. The problem now is that the new logger writes with both appenders, previous one and new one, while I want the new logger to write with the new appender only. Is there a way to tell LogManager.GetLogger(X) to bring only appenders that wee configured together with appender X?

1

There are 1 best solutions below

0
On BEST ANSWER

I have configured each dynamic logger to a separate repository, this way the logger contained only the appenders that were defined in the current config:

byte[] byteArray = Encoding.UTF8.GetBytes(sb.ToString());
MemoryStream stream = new MemoryStream(byteArray);
log4net.Repository.ILoggerRepository repository = log4net.LogManager.CreateRepository(logConfig.Type);
log4net.Config.XmlConfigurator.Configure(repository, stream);
ILog ilogRes = log4net.LogManager.GetLogger(repository.Name, logConfig.Type);