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
smtpAppender.ActivateOptions();
}
}


15 comments:

  1. 找一個懂妳的人也期許自己做一個人懂別人的人..................................................

    ReplyDelete
  2. 在莫非定律中有項笨蛋定律:「一個組織中的笨蛋,恆大於等於三分之二。」......................................................................

    ReplyDelete
  3. 向著星球長驅直進的人,反比踟躕在峽路上的人,更容易達到目的。............................................................

    ReplyDelete
  4. [做人難,人難做,難做人] 人.事的艱困與磨難,是一種考驗!要以樂觀歡喜之心,很珍惜地過每一天!^^............................................................

    ReplyDelete