Monday, May 24, 2010

Changing log4net configuration parameters at runtime

Since most of log4net configuration is specified in your application's configuration a question does come up on occasion how may I change this at runtime, depending on the user, etc.
Changing parameters at runtime for log4net is fairly simple - see the following code sample:

/// SMTP Appender custom configuration

public void InitializeLog4Net()
//We need access to the repositories for the loggers
ILoggerRepository repository = LogManager.GetRepository();

//Get only SmtpAppenders
//can do it as such:
//var appenders = repository.GetAppenders().Where(o => o is SmtpAppender).Select(o => (SmtpAppender)o);

//Or a bit more readable
var appenders= from o in repository.GetAppenders()
where o is SmtpAppender
select (SmtpAppender)o;

foreach (SmtpAppender smtpAppender in appenders)
smtpAppender.To = "adam_tuliper@nowhere";
//Make this config change active immediately

No comments:

Post a Comment

Note: Only a member of this blog may post a comment.